如何在Python中求和一个数组的列 [英] How to sum columns of an array in Python

查看:2304
本文介绍了如何在Python中求和一个数组的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将python数组中一列的所有值相加?理想情况下,我想这样做而不导入任何其他库.

How do I add up all of the values of a column in a python array? Ideally I want to do this without importing any additional libraries.

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

output_val = [3, 6, 9, 12, 15]

我知道我可以在嵌套的for循环中完成此操作,想知道是否有更好的方法(例如列表理解)?

I know I this can be done in a nested for loop, wondering if there was a better way (like a list comprehension)?

推荐答案

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]

这篇关于如何在Python中求和一个数组的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆