2012-07-25 62 views
7

名單的總和名單路口比方說,我有元組Python的最簡單的方式來元組

myList = [(1, 7), (3, 3), (5, 9)] 
otherList = [(2, 4), (3, 5), (5, 2), (7, 8)] 

returns => [(1, 7), (2, 4), (3, 8), (5, 11), (7, 8)] 

以下兩個列表,我想設計一個通過檢查的任何交叉合併這兩個清單合併操作元組的第一個元素,如果有交集,則添加每個元組的第二個元素(合併這兩個元素)。手術後,我想根據第一個元素進行分類。

我也張貼這是因爲我認爲它有一個明顯的解決方案一個很常見的問題,但我覺得有可能是對這個問題非常Python化的解決方案;)

回答

14

使用字典的結果:

result = {} 
for k, v in my_list + other_list: 
    result[k] = result.get(k, 0) + v 

如果你想要一個元組列表,你可以通過result.items()得到它。結果列表將以任意順序排列,但如果需要,當然可以對其進行排序。

(請注意,我改名爲你列出了與Python的風格約定符合)使用

+0

真的很乾淨。好的解決方案 – 2012-07-25 18:21:20

+0

請注意,'result.items()'將在Python 3中返回一個'dict_items'對象。當然,您始終可以執行'list(result.items())'。 – kamek 2012-07-25 20:43:03

1

的方法itertools:

>>> myList = [(1, 7), (3, 3), (5, 9)] 
>>> otherList = [(2, 4), (3, 5), (5, 2), (7, 8)] 

>>> import itertools 
>>> merged = [] 
>>> for k, g in itertools.groupby(sorted(myList + otherList), lambda e: e[0]): 
... merged.append((k, sum(e[1] for e in g))) 
... 
>>> merged 
[(1, 7), (2, 4), (3, 8), (5, 11), (7, 8)] 

兩個列表中這第一會連接在一起進行排序。 itertools.groupby返回合併列表的元素,按元組的第一個元素進行分組,所以它只是將它們彙總並放入合併列表中。

4

使用defaultdict:

from collections import defaultdict 
results_dict = defaultdict(int) 
results_dict.update(my_list) 
for a, b in other_list: 
    results_dict[a] += b 
results = sorted(results_dict.items()) 

注:排序序列,sorted排序由序列中的第一項。如果第一個元素相同,則它比較第二個元素。你可以給sorted一個函數來排序,使用key關鍵字參數:

results = sorted(results_dict.items(), key=lambda x: x[1]) #sort by the 2nd item 

results = sorted(results_dict.items(), key=lambda x: abs(x[0])) #sort by absolute value 
+0

(+1)我不知道這一次,我沒有意識到'dict.update'接受一個和dict構造函數相同的序列。另外,根據OP的要求對元組的第一項進行排序並不重要('results = sorted(results_dict.items())') – mgilson 2012-07-25 16:15:07

+0

@mgilson:謝謝!我錯過了關於排序結果的部分。將編輯。 – 2012-07-25 16:58:00

+0

@mgilson:顯然'update()'接受迭代器是在2.4中引入的。 – 2012-07-25 17:03:54

0
>>> [(k, sum(v for x,v in myList + otherList if k == x)) for k in dict(myList + otherList).keys()] 
[(1, 7), (2, 4), (3, 8), (5, 11), (7, 8)] 
>>> 

兩個Python2.7測試和3.2
dict(myList + otherList).keys()返回一個包含一個可迭代加入列表的密鑰集合
sum(...)需要'k'再次循環通過加入列表並添加元組項'v'其中k == x

...但額外的循環增加了處理開銷。使用Sven Marnach提出的明確字典避免了它。

相關問題