简体   繁体   中英

How to + the values in two lists of tuples

How can I add the tuples from two lists of tuples to get a new list of the results?

For example:

a = [(1,1),(2,2),(3,3)]   
b = [(1,1),(2,2),(3,3)]   

We want to get

c = [(2,2),(4,4),(6,6)]  

I searched google and found many results how to simply add two lists together using zip, but could not find anything about two lists of tuples.

use zip twice and a list comprehension:

In [63]: a = [(1,1),(2,2),(3,3)]

In [64]: b = [(1,1),(2,2),(3,3)]

In [66]: [tuple(map(sum, zip(x, y))) for x, y in zip(a, b)]
Out[66]: [(2, 2), (4, 4), (6, 6)]
>>> a = [(1,1),(2,2),(3,3)]
>>> b = [(1,1),(2,2),(3,3)]
>>> [(i[0]+j[0], i[1]+j[1]) for i, j in zip(a,b)]
[(2, 2), (4, 4), (6, 6)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM