简体   繁体   English

对列表列表中的整数求和

[英]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 .使用递归和isinstance function 我需要对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.但在这个例子中,我不知道如何使用 function 以递归方式进行操作。 I understand how isinstance works, but I have no idea how to use it in this example.我了解isinstance的工作原理,但我不知道如何在此示例中使用它。

In code below I don't even get different value than True.在下面的代码中,我什至没有得到与 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除外 output 是所有数字的总和

Recursion means you have to use a function.递归意味着您必须使用 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:您还可以将sum与递归一起使用:

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: Output:

55

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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