问题
I have the following code:
def flat_list(array):
d=[]
for i in array:
if not isinstance(i, list):
d.append(i)
else:
flat_list(i)
return d
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.
How do I use kindda (return d.append(i)
)?
回答1:
you call your function, but don't do anything with its return value when calling it recursively
else:
d.extend(flat_list(i))
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
Example
来源:https://stackoverflow.com/questions/58606878/recursion-problem-with-nested-lists-in-python