如何从两个元组列表中添加元组以获得新的结果列表?
例如:
a = [(1,1),(2,2),(3,3)]
b = [(1,1),(2,2),(3,3)]
我们想得到
c = [(2,2),(4,4),(6,6)]
我搜索了谷歌,发现了许多结果如何使用 zip 简单地将两个列表添加在一起,但找不到关于两个元组列表的任何信息。
使用zip
两次和一个列表理解:
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)]