查找嵌套的int列表的总和

Jac*_*ack 4 python python-3.x

import math
lists =  [1,[2,3],4]
total = 0
for i in range(len(lists)):
    total += sum(i)
print(total)
Run Code Online (Sandbox Code Playgroud)

我想要它打印,

>>>10
Run Code Online (Sandbox Code Playgroud)

但抛出一个错误.

我希望它能够添加所有数字,包括嵌套if中的数字.

kar*_*ikr 6

在你的程序中,for i in range(len(lists))- 当lists对象有3个元素时,计算结果为3 .并且在循环中total += sum(i)它会尝试执行int+ list操作,这会导致错误.因此,您需要检查类型,然后添加单个元素.

def list_sum(L):
    total = 0  
    for i in L:
        if isinstance(i, list): 
            total += list_sum(i)
        else:
            total += i
    return total
Run Code Online (Sandbox Code Playgroud)

这是@pavelanossov的评论 - 以更优雅的方式做同样的事情

sum(sum(i) if isinstance(i, list) else i for i in L)
Run Code Online (Sandbox Code Playgroud)


Far*_*hin 5

您可以在compiler.ast模块中使用flatten函数来展平列表.然后简单总结所有元素.

>>> lists =  [1,[2,3],4]
>>> from compiler.ast import flatten
>>> sum(flatten(lists))
10
Run Code Online (Sandbox Code Playgroud)

编辑:仅适用于Python 2.x.