How to recursively add items to a list?

我只是一个虾纸丫 提交于 2021-01-27 14:15:18

问题


Currently, I'm working on a problem. I am given a list, whose elements may contain other lists, lists of lists, or integers. For example, I may receive:

[[[[], 1, []], 2, [[], 3, []]], 4, [[[], 5, []], 6, [[], 7, [[], 9, []]]]]

My goal is to parse the array, and append only the integers to a new list. Here is what I have done so far:

def fun(a):
    if a == []:
        return None
    elif type(a) == int:
        print("Found a digit: ", a)
        return a
    for i in a:
        fun(i)

Currently, this function recursively goes through the list and successfully finds each integer; now, I am having an issue with appending those integers to a new list, and returning that list at the very end. The output should be like this:

[1,2,3,4,5,6,7,9]

Any pointers?


回答1:


Pass the list to append to as a parameter.

def fun(a, result):
    if type(a) == int:
        print("Found a digit: ", a)
        result.append(a)
    else:
        for i in a:
            fun(i, result)
old_list = [[[[], 1, []], 2, [[], 3, []]], 4, [[[], 5, []], 6, [[], 7, [[], 9, []]]]]
new_list = []
fun(old_list, new_list)
print(new_list)

If you need the original function signature, you can split this into two functions.

def fun(a):
    result = []
    fun_recursive(a, result)
    return result

fun_recursive() would be defined as above.




回答2:


you can try:

def fun(a):
    if isinstance(a, int):
        yield a
    else:
        for e in a:
            yield from fun(e)

print(list(fun([[[[], 1, []], 2, [[], 3, []]], 4, [[[], 5, []], 6, [[], 7, [[], 9, []]]]])))

output:

[1, 2, 3, 4, 5, 6, 7, 9]


来源:https://stackoverflow.com/questions/58174992/how-to-recursively-add-items-to-a-list

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