Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 做这个总数的非理解列表方法是什么_Python_Sum_List Comprehension_Nested Lists - Fatal编程技术网

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