Python 做这个总数的非理解列表方法是什么
这是欧也妮在以下帖子中给出的解决方案: 我只是想在不使用理解列表的情况下重新创建它,但我无法获得它。我该怎么做呢?代码使用了一个,而不是一个列表 使用循环并将结果相加:Python 做这个总数的非理解列表方法是什么,python,sum,list-comprehension,nested-lists,Python,Sum,List Comprehension,Nested Lists,这是欧也妮在以下帖子中给出的解决方案: 我只是想在不使用理解列表的情况下重新创建它,但我无法获得它。我该怎么做呢?代码使用了一个,而不是一个列表 使用循环并将结果相加: def nested_sum(L): return sum( nested_sum(x) if isinstance(x, list) else x for x in L ) 或者,如果要将该语句扩展为if语句: def nested_sum(L): total = 0 for x in L:
def nested_sum(L):
return sum( nested_sum(x) if isinstance(x, list) else x for x in L )
或者,如果要将该语句扩展为if
语句:
def nested_sum(L):
total = 0
for x in L:
total += nested_sum(x) if isinstance(x, list) else x
return total
@ezitoc:答案中有什么遗漏,你又不接受了吗?:-)谢谢,我在找“条件表达式”关键字。我对这个很陌生。生成器表达式对我来说也是新的。起初是的,但后来我发现了我刚才评论的内容:)
def nested_sum(L):
total = 0
for x in L:
if isinstance(x, list):
total += nested_sum(x)
else:
total += x
return total