![](/img/trans.png)
[英]How to make a list of integers that is the sum of all the integers from a set of lists in a dict?
[英]Sum integers from a list of lists
我有一個
table = [7, 5, [3, 6, [2]], 7, [1, [2, 3, [4]], 9, 2], 4]
使用遞歸和isinstance
function 我需要對table
的所有整數求和。 我可以創建新列表,通過表中的列表擴展它。 然后我得到了一個普通的列表(列表中沒有列表),我可以總結它。
但在這個例子中,我不知道如何使用 function 以遞歸方式進行操作。 我了解isinstance
的工作原理,但我不知道如何在此示例中使用它。
在下面的代碼中,我什至沒有得到與 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))
除外 output 是所有數字的總和
遞歸意味着您必須使用 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))
您還可以將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:
55
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.