gpt4 book ai didi

python - Python 中的递归函数悖论.. 如何解释?

转载 作者:行者123 更新时间:2023-11-28 22:49:36 24 4
gpt4 key购买 nike

我做了一个非常简单的函数,它接受一个数字列表并返回一个由一些数字四舍五入的数字列表:

def rounded(lista, digits = 3):
neulist = []
for i in lista:
neulist.append(round(i, digits))
return neulist

但是,我错误地将函数本身放在代码中,而不是内置的 round()(如下例所示):

def rounded(lista, digits = 3):
neulist = []
for i in lista:
neulist.append(rounded(i, digits))
return neulist

得到这个输出:

Traceback (most recent call last):
File "<pyshell#286>", line 1, in <module>
rounded(a)
File "<pyshell#284>", line 4, in rounded
neulist.append(rounded(i, digits))
File "<pyshell#284>", line 3, in rounded
for i in lista:
TypeError: 'float' object is not iterable

问题是:解释器如何知道它必须在评估函数 rounded() 本身时应用函数 rounded()?如果 rounded() 是一个接受 float 的函数,如果它试图解释那个函数,怎么可能呢?是否有一种用于评估和解释功能的双循环程序?或者我在这里弄错了什么?

最佳答案

函数是一个对象。它是在定义时创建的,而不是在调用时创建的,因此如果 Python 不知道如何使用它,它会在任何调用完成之前引发错误。
但是,您使用列表调用它。在迭代期间,使用列表的第一项递归调用该函数——大概是一个 float 。使用此 float 作为参数,for i in lista: 不再有意义,并且出现错误。

关于python - Python 中的递归函数悖论.. 如何解释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23638328/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com