Python 正在函数调用之间保存本地对象值(可能是作用域错误)
我在试图解决一个“扁平化”列表的任务时感到困惑Python 正在函数调用之间保存本地对象值(可能是作用域错误),python,recursion,return,scopes,Python,Recursion,Return,Scopes,我在试图解决一个“扁平化”列表的任务时感到困惑 例如,我有一个列表[1,2,2,2,4]——我需要将它转换为[1,2,2,2,4]。我这样解决了它: def flat_list(array, temp_list=[]): for item in array: if str(item).isdigit(): temp_list.append(item) else: temp_list = flat_list(i
例如,我有一个列表[1,2,2,2,4]——我需要将它转换为[1,2,2,2,4]。
我这样解决了它:
def flat_list(array, temp_list=[]):
for item in array:
if str(item).isdigit():
temp_list.append(item)
else:
temp_list = flat_list(item, temp_list)
return temp_list
但当我测试它时:
assert flat_list([1, 2, 3]) == [1, 2, 3]
assert flat_list([1, [2, 2, 2], 4]) == [1, 2, 2, 2, 4]
assert flat_list([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) == [2, 4, 5, 6, 6, 6, 6, 6, 7]
“临时列表”的值在函数调用之间传输。第二个断言开头的“temp_list”的值是[1,2,3]——第一个断言的“return”值——但不是“[]”
我猜,这是因为我对作用域和“return”指令有一些误解,但我不清楚到底是什么。这是Python中的一个已知问题 当且仅当 执行它们所属的“def”语句 参考: 在代码示例中,执行
def
语句时,将计算temp\u列表的默认值。因此它被设置为一个空列表。在随后的调用中,列表只会不断增长,因为不再计算temp_list
的默认值,而是继续使用它第一次创建的列表实例
这可能是一个解决办法:
def flat_list(array, temp_list=None):
if not temp_list:
temp_list = []
for item in array:
if str(item).isdigit():
temp_list.append(item)
else:
temp_list = flat_list(item, temp_list)
return temp_list
这里,我们传递的是None
,而不是空列表。然后在函数体内,我们检查值并根据需要初始化一个空列表 是的,您正在断言这些函数调用返回的值。因此,这是同一个函数的多次执行。每个后续断言都会获取前一个断言的返回值?我需要阅读你的“ref”,因为我理解)每个断言调用函数一次。