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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14180866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:41:29  来源:igfitidea点击:

sum each value in a list of tuples

pythonperformancelistpython-2.7list-comprehension

提问by Inbar Rose

I have a list of tuples similar to this:

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

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

I want to create a simple one-liner that will give me the following result:

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

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

Which would be like doing the following:

这就像执行以下操作:

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

I am sure it is something very simple, but I can't think of it.

我相信这是非常简单的事情,但我想不出来。

Note: I looked at similar questions already:

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

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?

如何在 Python 中的元组列表中对每个元组中的第一个值求和?

采纳答案by Ashwini Chaudhary

Use zip()and sum():

使用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]

or:

或者:

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

timeitresults:

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

回答by Alessandro Ruffolo

I want to add something to the given answer:

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

If I have an array of dict e.g.

如果我有一个字典数组,例如

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

and i want to obtain two (or more) sums of calculated quantity over the values e.g. sum of quantities and of price*quantity

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

I can do:

我可以:

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

Instead of:

代替:

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

Maybe the first solution is less readable, but is more "pythonesque" :)

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

回答by cipilo

Without using zip

不使用zip

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