【发布时间】:2017-04-11 15:31:03
【问题描述】:
我希望结合使用递归和 for 循环,使用函数 summer(alist) 将所有整数添加到可能为空的一系列嵌套列表中。到目前为止我的代码是:
**def summer(alist):**
total=0
print alist
for item in alist:
if type(item)==list:
print "The item is a list, containing: "+str(item)
return sum_nested_list(item)
elif type(item)==int:
print item
total = total + item
print "The total is: "+str(total)
return total
我的问题是例如列表:
list1=[[0,[0,1,1]],[0,1],1]
我的结果是这样的:
[[0,[0,1,1]],[0,1],1]
The item is a list, containing: [0,[0,1,1]]
[0,[0,1,1]]
0
The item is a list, containing [0,1,1]
[0,1,1]
0
1
1
The total is: 2
2
如何让我的函数在整个列表上递归,而不仅仅是第一个双嵌套列表?
【问题讨论】:
-
问题是你的
return语句结束了for循环 -
啊,明白了。我现在会尝试删除它。
-
刚刚发布了一个可能的修复...
-
啊,谢谢!我尝试删除退货,只是让我的
sum_nested_list(item)冷落,总数只会更新每件商品,而不会在它们之间保持一致。非常感谢您的回答!
标签: python list recursion nested