Python中嵌套列表的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14917092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sum of nested list in Python
提问by Jin
I try to sum a list of nested elements
我尝试对嵌套元素列表求和
e.g, numbers=[1,3,5,6,[7,8]]should produce sum=30
例如,numbers=[1,3,5,6,[7,8]]应该产生sum=30
I wrote the following code :
我写了以下代码:
def nested_sum(L):
sum=0
for i in range(len(L)):
if (len(L[i])>1):
sum=sum+nested_sum(L[i])
else:
sum=sum+L[i]
return sum
The above code gives following error:
上面的代码给出了以下错误:
object of type 'int' has no len()
“int”类型的对象没有 len()
I also tried len([L[i]]), still not working.
我也试过了len([L[i]]),还是不行。
Anyone can help? It is Python 3.3
任何人都可以帮忙吗?它是 Python 3.3
采纳答案by Volatility
You need to use isinstanceto check whether an element is a list or not. Also, you might want to iterate over the actual list, to make things simpler.
您需要使用isinstance来检查元素是否为列表。此外,您可能想要遍历实际列表,以使事情更简单。
def nested_sum(L):
total = 0 # don't use `sum` as a variable name
for i in L:
if isinstance(i, list): # checks if `i` is a list
total += nested_sum(i)
else:
total += i
return total
回答by Volatility
One alternative solution with list comprehension:
具有列表理解的另一种解决方案:
>>> sum( sum(x) if isinstance(x, list) else x for x in L )
30
Edit: And for lists with more than two levels(thx @Volatility):
编辑:对于超过两个级别的列表(thx @Volatility):
def nested_sum(L):
return sum( nested_sum(x) if isinstance(x, list) else x for x in L )
回答by Jaime
It is generally considered more pythonic to duck type, rather than explicit type checking. Something like this will take any iterable, not just lists:
通常认为鸭子类型更像 Pythonic ,而不是显式类型检查。像这样的东西将需要任何可迭代的,而不仅仅是列表:
def nested_sum(a) :
total = 0
for item in a :
try:
total += item
except TypeError:
total += nested_sum(item)
return total
回答by dansalmo
I would sum the flattened list:
我会总结扁平化的列表:
def flatten(L):
'''Flattens nested lists or tuples with non-string items'''
for item in L:
try:
for i in flatten(item):
yield i
except TypeError:
yield item
>>> sum(flatten([1,3,5,6,[7,8]]))
30
回答by Broseph
An example using filter and map and recursion:
使用过滤器和映射以及递归的示例:
def islist(x):
return isinstance(x, list)
def notlist(x):
return not isinstance(x, list)
def nested_sum(seq):
return sum(filter(notlist, seq)) + map(nested_sum, filter(islist, seq))
And here is an example using reduce and recursion
这是一个使用减少和递归的例子
from functools import reduce
def nested_sum(seq):
return reduce(lambda a,b: a+(nested_sum(b) if isinstance(b, list) else b), seq)
An example using plain old recursion:
使用普通旧递归的示例:
def nested_sum(seq):
if isinstance(seq[0], list):
head = nested_sum(seq[0])
else:
head = seq[0]
return head + nested_sum(seq[1:])
An example using simulated recursion:
使用模拟递归的示例:
def nested_sum(seq):
stack = []
stack.append(seq)
result = 0
while stack:
item = stack.pop()
if isinstance(item, list):
for e in item:
stack.append(e)
else:
result += item
return result
Adjustment for handling self-referential lists is left as an exercise for the reader.
处理自引用列表的调整留给读者作为练习。
回答by njzk2
A quick recursion that uses a lambda to handle the nested lists:
使用 lambda 处理嵌套列表的快速递归:
rec = lambda x: sum(map(rec, x)) if isinstance(x, list) else x
rec, applied on a list, will return the sum (recursively), on a value, return the value.
rec,应用于列表,将返回总和(递归),在一个值上,返回该值。
result = rec(a)
回答by yashraj
This code also works.
此代码也有效。
def add_all(t):
total = 0
for i in t:
if type(i) == list: # check whether i is list or not
total = total + add_all(i)
else:
total += i
return total
回答by Alessandro Anderson
def nnl(nl): # non nested list function
nn = []
for x in nl:
if type(x) == type(5):
nn.append(x)
if type(x) == type([]):
n = nnl(x)
for y in n:
nn.append(y)
return sum(nn)
print(nnl([[9, 4, 5], [3, 8,[5]], 6])) # output:[9,4,5,3,8,5,6]
a = sum(nnl([[9, 4, 5], [3, 8,[5]], 6]))
print (a) # output: 40
回答by Sam Franklin
A simple solution would be to use nested loops.
一个简单的解决方案是使用嵌套循环。
def nested_sum(t):
sum=0
for i in t:
if isinstance(i, list):
for j in i:
sum +=j
else:
sum += i
return sum
回答by Sumi
def nested_sum(lists):
total = 0
for lst in lists:
s = sum(lst)
total += s
return total

