简体   繁体   中英

How to recursively add items to a list?

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?

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM