如何找到嵌套列表中元素的总和?

How to find the sum of elements in nested list?

下面是给定的列表:

x = [[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]]

我这里需要的是不同列表中每个嵌套列表的数字之和。

例如[162,163,.....]

>>> x = [[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]]
>>> y = [sum(i) for i in x]
>>> y
[162, 163, 165, 165, 167, 168, 170, 172, 173, 175]

只需循环遍历项目。

首先你遍历内部列表:

for lst in x:

然后使用 sum 方法对列表中的项目求和: 总计 = 总和(lst)

放在一起看起来像这样:

new_list = list()
for lst in x:
    lst = sum(lst)
    new_list.append(total)

print(new_list)

希望这对您有所帮助。

编辑:我以前没用过sum方法。这就是为什么尽管程序运行良好,但还是有两次投反对票。

你可以简单地做:

x = [[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]]

print(list(map(sum,x)))

输出:

[162, 163, 165, 165, 167, 168, 170, 172, 173, 175]