python中嵌套列表的递归问题 [英] recursion problem with nested lists in python
问题描述
我有以下代码:
def flat_list(array):
d=[]
for i in array:
if not isinstance(i, list):
d.append(i)
else:
flat_list(i)
return d
当我呼叫flat_list([1, [2, 2, 2], 4])
时,我希望它返回未压缩的列表([1、2、2、2、4]).相反,它返回([1,4]).虽然,如果我尝试使用(print i)
而不是(d.append(i))
,它将返回解压后的i.
When I call flat_list([1, [2, 2, 2], 4])
, I expect it to return unpacked list ([1, 2, 2, 2, 4]). Instead it returns ([1, 4]). Although, if I try (print i)
instead of (d.append(i))
, it returns unpacked i.
我阅读了关于递归的一篇文章,其中说了返回需求在基本条件之后.
I read an article about recursion, it says return needs to be after base condition.
如何使用kindda(return d.append(i)
)?
How do I use kindda (return d.append(i)
)?
推荐答案
您调用函数,但是在递归调用函数时不对其返回值做任何操作
you call your function, but don't do anything with its return value when calling it recursively
else:
d.extend(flat_list(i))
extend
将从flat_list
返回的列表中取出所有项目,并将它们添加到您在函数中创建的列表中
extend
will take all the items from the list that flat_list
returns, and adds them to your list you are creating within the function
这篇关于python中嵌套列表的递归问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!