我想添加包含元组的列表的每个元素。例如,
>>> 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)]
答案 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))]