对元组列表中的每个值求和

时间:2013-01-06 09:32:43

标签: python performance list python-2.7 list-comprehension

我有一个与此类似的元组列表:

l = [(1, 2), (3, 4), (5, 6), (7, 8), (9, 0)]

我想创建一个简单的单行程序,它会给我以下结果:

r = (25, 20) or r = [25, 20] # don't care if tuple or list.

这就像执行以下操作:

r = [0, 0]
for t in l:
  r[0]+=t[0]
  r[1]+=t[1]

我确信这很简单,但我想不出来。

注意:我已经查看了类似的问题:

How do I sum the first value in a set of lists within a tuple?

How do I sum the first value in each tuple in a list of tuples in Python?

3 个答案:

答案 0 :(得分:49)

使用zip()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]

或:

In [4]: map(sum, zip(*l))
Out[4]: [25, 20]

timeit结果:

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

答案 1 :(得分:2)

我想在给定答案中添加一些内容:

如果我有一系列dict,例如

l = [{'quantity': 10, 'price': 5},{'quantity': 6, 'price': 15},{'quantity': 2, 'price': 3},{'quantity': 100, 'price': 2}]

我希望获得两个(或更多)计算数量的总和,例如数量和价格总和*数量

我能做到:

(total_quantity, total_price) = (
sum(x) for x in zip(*((item['quantity'],
                       item['price'] * item['quantity'])
                      for item in l)))

而不是:

total_quantity = 0
total_price = 0
for item in l:
     total_quantity += item['quantity']
     total_price += item['price'] * item['quantity']

也许第一种解决方案的可读性较差,但更“pythonesque”:)

答案 2 :(得分:1)

不使用zip

sum(e[0] for e in l), sum(e[1] for e in l)