且构网

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

如何在Python中求和一个数组的列

更新时间:2023-02-05 13:18:52

zipsum可以做到:

代码:

[sum(x) for x in zip(*input_val)]

zip接受输入列表的内容并转置它们,以便同时生成所包含列表的每个元素.这使sum可以看到每个包含列表的第一个元素,然后下一次迭代将获得每个列表的第二个元素,依此类推...

zip takes the contents of the input list and transposes them so that each element of the contained lists is produced at the same time. This allows the sum to see the first elements of each contained list, then next iteration will get the second element of each list, etc...

测试代码:

input_val = [[1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5],
             [1, 2, 3, 4, 5]]

print([sum(x) for x in zip(*input_val)])

结果:

[3, 6, 9, 12, 15]