Use zip()
and sum()
:
In [1]: l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]
In [2]: [sum(x) for x in zip(*l)]
Out[2]: [25, 20]
or:
In [4]: map(sum, zip(*l))
Out[4]: [25, 20]
timeit
results:
In [16]: l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]*1000
In [17]: %timeit [sum(x) for x in zip(*l)]
1000 loops, best of 3: 1.46 ms per loop
In [18]: %timeit [sum(x) for x in izip(*l)] #prefer itertools.izip
1000 loops, best of 3: 1.28 ms per loop
In [19]: %timeit map(sum, zip(*l))
100 loops, best of 3: 1.48 ms per loop
In [20]: %timeit map(sum, izip(*l)) #prefer itertools.izip
1000 loops, best of 3: 1.29 ms per loop
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…