[英]adding tuple elements in a list
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
形成的dict並迭代l2
來輕松完成,請參閱下面的工作代碼片段:
l1=[(2,1),(3,2),(4,5)]
l2=[(2,3),(3,6),(11,3)]
result = dict(l1)
for y in l2:
result[y[0]] = result.get(y[0],0) + y[1]
result = result.items()
print result #[(11, 3), (2, 4), (3, 8), (4, 5)]
或者只是通過迭代l1
和l2
連接來構建結果:
l1=[(2,1),(3,2),(4,5)]
l2=[(2,3),(3,6),(11,3)]
result = {}
for item in l1 + l2:
result[item[0]] = result.get(item[0],0) + item[1]
祝好運!
如果我理解你的目的,就沒有必要為l1
所有元素都經過l2
的元素。 只需使用zip
(或izip_longest
如果列表的大小不均勻)使用每個列表中的元組,然后append
第一個項目和總和,如果第一個項目匹配並extend
兩個元組,如果他們不:
for tup1, tup2 in zip(l1, l2):
if tup1[0] == tup2[0]:
result.append((tup1[0], (tup1[1] + tup2[1])))
else:
result.extend([tup1, tup2])
輸入后,返回所需的輸出:
>>> 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)]
似乎很自然地使用字典來跟蹤已經使用的鍵。 您可以使用defaultdict
減小代碼大小:
import collections
l1=[(2,1),(3,2),(4,5)]
l2=[(2,3),(3,6),(11,3)]
d = collections.defaultdict(int)
for x,y in l1 + l2:
d[x] += y
print sorted(d.items())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.