首页 > 解决方案 > 如何使用 Python 添加数组

问题描述

给定一个使用 Python 3 的数组a = [1,2,3,[4,5]],如何添加数组中的所有元素?

sum(a[0])
sun(a[0][1])

上面的代码不起作用。同样在这种情况下,如果给定一个数组,其中数组中的数组数量未知,那么如何计算这些数字?

标签: python

解决方案


def xsum(x):
    if not x:
        return 0

    head, *tail = x

    if isinstance(head, list):
        return xsum(head) + xsum(tail)
    elif tail:
        return head + xsum(tail)
    else:
        return head

推荐阅读