recursion problem with nested lists in python

对着背影说爱祢 提交于 2019-12-12 20:02:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!