Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 575
Anonymous Entity Avatar asked Apr 28 '13 19:04

Anonymous Entity


1 Answers

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)]
like image 132
Ashwini Chaudhary Avatar answered Sep 19 '22 22:09

Ashwini Chaudhary