如何计算列表中所有元素的总和。列表中的元素可以是整数或嵌套列表

问题描述 投票:0回答:1
def calculate_total_sum(arr):
    # Your code here
    sum=0
    for i in range(len(arr)):
        for j in range(len(arr[i])):
            sum=sum+arr[i][j]
    print(sum)

list1=[int(x) for x in input().split()]
calculate_total_sum(list1)

运行代码时出现错误 -

unsupported operand type(s) for +: 'int' and 'str'

python list multidimensional-array
1个回答
0
投票

我们可以在这里使用dfs:

def calculate_total_sum(arr):
    def dfs(arr, total):
        if arr is None:
            return total
        if type(arr) == int:
            return total + arr
        for el in arr:
            total = dfs(el, total)
        return total
    total = 0
    return dfs(arr, total)


list1 = [3, 3, [[3, 3, [3, [3, [3, [3, [3, [3, [3, 3, 3]]]]]]], 3]]]
print(calculate_total_sum(list1))
© www.soinside.com 2019 - 2024. All rights reserved.