l1=[(2,1),(3,2),(4,5)]
l2=[(2,3),(3,6),(11,3)]
我需要:
result=[(2,4),(3,8),(4,5),(11,3)]
使用for循环我能够添加具有相同第一个元素的元组.
>>> result = []
l1 = [(2, 1), (3, 2), (4, 5)]
l2 = [(2, 3), (3, 6), (11, 3)]
for x, y in l1:
for p, q in l2:
if x == p:
result.append((x, (y + q)))
>>> result
[(2, 4), (3, 8)]
我如何进一步添加(4,5),(11,3)
最佳答案 实现相同目标的方法很多……我喜欢它!
这是我的解决方案.
l1=[(2,1),(3,2),(4,5)]
l2=[(2,3),(3,6),(11,3)]
d1 = dict(l1)
d2 = dict(l2)
result = []
for k in d1:
if k in d2:
result.append((k,d1[k]+d2[k]))
else:
result.append((k,d1[k]))
for k in d2:
if k not in d1:
result.append((k,d2[k]))
>>>print result
[(2, 4), (3, 8), (4, 5), (11, 3)]