对元组列表中的每个值求和 [英] sum each value in a list of tuples

查看:37
本文介绍了对元组列表中的每个值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这会像执行以下操作:

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:

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

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

推荐答案

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

这篇关于对元组列表中的每个值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆