我尝试总结嵌套元素列表
例如,数字= [1,3,5,6,[7,8]],sum = 30
我写了以下代码
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
上面的代码给出了以下错误:'int'类型的对象没有len() 我也试过len([L [i]]),仍然没有工作
任何人都可以提供帮助?顺便说一下,它是Python 3.3
答案 0 :(得分:24)
您需要使用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
答案 1 :(得分:5)
通常认为duck type更加pythonic,而不是显式类型检查。像这样的东西将采用任何可迭代的,而不仅仅是列表:
def nested_sum(a) :
total = 0
for item in a :
try:
total += item
except TypeError:
total += nested_sum(item)
return total
答案 2 :(得分:4)
使用lambda处理嵌套列表的快速递归:
rec = lambda x: sum(map(rec, x)) if isinstance(x, list) else x
应用于列表的 rec
将返回值(递归),返回值。返回值。
result = rec(a)
答案 3 :(得分:3)
我总结一下这个扁平化的清单:
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
答案 4 :(得分:2)
列表理解的另一种解决方案:
>>> sum( sum(x) if isinstance(x, list) else x for x in L )
30
编辑: 对于具有两个以上级别的列表(thx @Volatility):
def nested_sum(L):
return sum( nested_sum(x) if isinstance(x, list) else x for x in L )
答案 5 :(得分:1)
使用过滤器,地图和递归的示例:
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))
以下是使用reduce和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)
使用普通旧递归的示例:
def nested_sum(seq):
if isinstance(seq[0], list):
head = nested_sum(seq[0])
else:
head = seq[0]
return head + nested_sum(seq[1:])
使用模拟递归的示例:
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
处理自助参考名单的调整留给读者练习。
答案 6 :(得分:1)
此代码也有效。
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
答案 7 :(得分:1)
def sum_nest_lst(lst):
t=0
for l in lst:
if(type(l)==int):
t=t+l
if(type(l)==list):
t=t+sum(l)
print(t)
答案 8 :(得分:0)
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
答案 9 :(得分:0)
一个简单的解决方案是使用嵌套循环。
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
答案 10 :(得分:0)
def nested_sum(lists):
total = 0
for lst in lists:
s = sum(lst)
total += s
return total
答案 11 :(得分:0)
L = [1, 2, 3, [4, 5, 6], 5, [7, 8, 9]]
total = 0 # assign any var
for a in L: # assign index and start to iterate using if else
if (isinstance(a, list)): # since its a list you are basically repeating the prev step
for b in a:
total += b
else:
total += a
print(total)
答案 12 :(得分:0)
def list_sum(L):
return sum(list_sum(x) if isinstance(x, list) else x for x in L)
答案 13 :(得分:-2)
#nested sum
l = [[1, 2], [3,5], [6,2], [4, 5, 6,9]]
def nested_sum(lst):
sum = 0
for i in lst:
for j in i:
sum = sum + j
print(sum)
nested_sum(l)