I want to add each element of list containing tuples. For example,
>>> list1
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list2
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Answer should be
list3 = [(1,3,5),(7,9,11),(13,15,17)]
I want to add each element of list containing tuples. For example,
>>> list1
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list2
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
Answer should be
list3 = [(1,3,5),(7,9,11),(13,15,17)]
zip is your friend here.
result = []
for ta, tb in zip(list1, list2):
t =tuple(a+b for a, b in zip(ta, tb))
result.append(t)
print result
>> [(1,3,5),(7,9,11),(13,15,17)]
or more pythonic is:
result = [tuple(a+b for a, b in zip(ta, tb)) for ta, tb in zip(list1, list2)]
print result
>> [(1,3,5),(7,9,11),(13,15,17)]
result could simply be a generator by doing this:
result = (tuple(a+b for a, b in zip(ta, tb)) for ta, tb in zip(list1, list2))
>>> list1 = [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list2 = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
>>> [tuple(map(sum, zip(*i))) for i in zip(list1, list2)]
[(1, 3, 5), (7, 9, 11), (13, 15, 17)]
The nice thing about doing it this way is that it also works for an arbitrary number of lists
>>> list3 = [tuple(map(sum, zip(*i))) for i in zip(list1, list2)]
>>> [tuple(map(sum, zip(*i))) for i in zip(list1, list2, list3)]
[(2, 6, 10), (14, 18, 22), (26, 30, 34)]
You can use a list comprehension, though it's a bit awkward:
list3 = [tuple(x + y for x, y in zip(t1, t2))
for t1, t2 in zip(list1, list2)]
If you are fine with a list of lists instead of a lists of tuples, an alternative is
list3 = [map(operator.add, *t) for t in zip(list1, list2)]
tuple() around imap() if he really needs a tuple.Edit: The below is not at all needed. The map builtin automatically zips multiple iterables passed to it, so zip_with(func, iter1, iter2) can be replaced by map with the same arguments.
map(functools.partial(map, op.add), list1, list2)
Here's a snippet implementing something along the lines of Haskell's zipWith
def zip_with(func, xs, ys):
return [func(x, y) for (x, y) in zip(xs, ys)]
In [1]: def zip_with(func, xs, ys):
...: return [func(x, y) for (x, y) in zip(xs, ys)]
...:
In [2]: import operator as op
In [3]: zip_with(op.add, [1,2,3], [4,5,6])
Out[3]: [5, 7, 9]
In [4]: import functools
In [5]: zip_with(functools.partial(zip_with, op.add), list1, list2)
Out[5]: [[1, 3, 5], [7, 9, 11], [13, 15, 17]]