且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python中嵌套列表的总和

更新时间:2023-11-28 23:39:04

您需要使用isinstance来检查元素是否为列表.另外,您可能希望遍历实际列表,以使事情变得更简单.

You need to use isinstance to check whether an element is a list or not. Also, you might want to iterate over the actual list, to make things simpler.

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