[英]Quick way to sum the ith item of a list of lists in python
I am looking for an alternative approach of summing the ith item of a list of lists that is feasible over large data sets. 我正在寻找一种对大型数据集可行的汇总列表第i个项的替代方法。 Below is an example list and my approach.
以下是示例列表和我的方法。
j=[[1,2,3],[3,2,1],[2,1,3]]
My attempt:
h_0=zip(j[0],j[1],j[2])
h_1=[sum(x) for x in h]
print h_1
Output: [6, 5, 7]
Desired output:[6, 5, 7]
....the same as the output I got but would prefer a different approach as my approach is not feasible given the size of my actual data. Desired output:[6, 5, 7]
....与我得到的输出相同,但是由于我的方法在给定实际数据量的基础上不可行,因此希望使用其他方法。
Thanks for your suggestions. 感谢您的建议。
Use zip
with *
-operator (unpacking argument list) : 将
zip
与*
-operator一起使用(解 zip
参数列表) :
>>> j = [[1,2,3],[3,2,1],[2,1,3]]
>>> zip(*j)
[(1, 3, 2), (2, 2, 1), (3, 1, 3)]
>>> map(sum, zip(*j))
[6, 5, 7]
>>> list(map(sum, zip(*j))) # In Python 3.x
[6, 5, 7]
using list comprehension: 使用列表理解:
>>> [sum(cols) for cols in zip(*j)]
[6, 5, 7]
>>> a = np.array(j)
>>> a.sum(axis=0)
array([6, 5, 7])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.