python元组列表中每个元素的总和

时间:2012-02-22 22:35:15

标签: python list tuples

我想添加包含元组的列表的每个元素。例如,

    >>> list1
    [(0, 1, 2), (3, 4, 5), (6, 7, 8)]
    >>> list2
    [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

答案应该是

     list3 = [(1,3,5),(7,9,11),(13,15,17)]

6 个答案:

答案 0 :(得分:8)

zip是你的朋友。

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)]

或更多pythonic是:

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 = (tuple(a+b for a, b in zip(ta, tb)) for ta, tb in zip(list1, list2))

答案 1 :(得分:4)

>>> 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)]

这样做的好处是,它也适用于任意数量的列表

>>> 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)]

答案 2 :(得分:3)

你可以使用列表理解,虽然它有点尴尬:

list3 = [tuple(x + y for x, y in zip(t1, t2))
         for t1, t2 in zip(list1, list2)]

如果你对列表列表而不是元组列表没问题,可以选择

list3 = [map(operator.add, *t) for t in zip(list1, list2)]

答案 3 :(得分:1)

>>> [tuple(sum(pair) for pair in zip(a,b)) for a,b in zip(list1,list2)]
[(1, 3, 5), (7, 9, 11), (13, 15, 17)]

答案 4 :(得分:1)

编辑:以下根本不需要。 map内置函数会自动压缩传递给它的多个迭代,因此zip_with(func, iter1, iter2)可以用map替换为相同的参数。

map(functools.partial(map, op.add), list1, list2)

不需要此部分

这是一个实现Haskell 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]]

答案 5 :(得分:-1)

import operator
list3 = [tuple(map(operator.add, list1[i], list2[i]))
 for i in range(len(list1))]