简体   繁体   中英

Sum integers from a list of lists

I have a

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

Using recursion and the isinstance function I need to sum all integers in table . I can do it creating new list, extending it by lists from table. Then I got a normal list (no list in lists) and I can sum it.

But in this example I have no idea how to do it in a recursive way using that function. I understand how isinstance works, but I have no idea how to use it in this example.

In code below I don't even get different value than True.

tab = [7, 5, [3, 6, [2]], 7, [1, [2, 3, [4]], 9, 2], 4]
for i in range(len(tab)):
    print(isinstance(i, int))

Excepted output is sum of all numbers

Recursion means you have to use a function.

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

def int_sum(tbl):
    s = 0
    for e in tbl:
        if isinstance(e, int):
            s += e
        else:
            # this is the trick!
            s += int_sum(e)
    return s

print(int_sum(tab))

You can also use sum with recursion:

table = [7, 5, [3, 6, [2]], 7, [1, [2, 3, [4]], 9, 2], 4]
def get_sum(d):
  return sum(i if isinstance(i, int) else get_sum(i) for i in d)

print(get_sum(table))

Output:

55

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