Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

python - sum each value in a list of tuples

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...