我想获得列表中两个不同值的总和。例如:
sample = [(1,3), (4,5), (8,2)]
我希望输出是
13, 10
我可以通过几种不同的方式来做到这一点。这是我目前的方式:
t1 = 0
t2 = 0
for item1, item2 in sample:
t1 += item1
t2 += item2
解决这个问题的更 Pythonic 的方法是什么?
你可以试试这个:
from itertools import izip
sample = [(1,3), (4,5), (8,2)]
t1, t2 = map(sum, izip(*sample))
您还可以使用列表推导来代替map
.
from itertools import izip
sample = [(1,3), (4,5), (8,2)]
t1, t2 = [sum(t) for t in izip(*sample)]
您可以处理两个以上的金额:
from itertools import izip
sample = [(1, 3, 1), (4, 5, 1), (8, 2, 1)]
sums = [sum(t) for t in izip(*sample)]
# sums == [13, 10, 3]
一种功能性方法:
from operator import add
from functools import partial
sample = [(1,3), (4,5), (8,2)]
result = reduce(partial(map, add), sample)
result
将是[13, 10]
运行此代码后的列表。
sample = [(1,3), (4,5), (8,2)]
r1 = 0
r2 = 0
for v in sample:
r1, r2 = r1+v[0], r2+v[1]
print r1, r2
虽然@FastTurtle 更酷。
单线:
sum([ x[0] for x in sample ]), sum([ x[1] for x in sample ])
或者对于未知维度的列表:
map(lambda i: sum(x[i] for x in sample), range(len(sample[0])))
如果您要经常这样做(在大型数据集上),numpy
将会很有帮助。
>>> from numpy import *
>>> sample = [(1,3), (4,5), (8,2)]
>>> sum(array(sample), axis=1)
array([ 4, 9, 10])
>>> sum(array(sample), axis=0)
array([13, 10])