2012-11-22 28 views

回答

-2

這裏的強制性單行itertools解決方案:

>>> import itertools 
>>> [ 
... (k, sum(g[1] for g in group)) 
... for k, group in itertools.groupby(sorted(L), key=lambda x: x[0]) 
... ] 
[('a', 5), ('b', 5), ('c', 7)] 
+0

@thg:我在測試之前發佈了,並且犯了一個錯誤,我顯然被懲罰了。需要'key = lambda x:x [0]'_is_。你得到了[(('',2),2),(('',3),3),(('',1),1),(('b',4),4 ),(('c',2),2),(('c',5),5)]'沒有它 – Eric

+2

首先你對它進行排序,然後你將它分組,調用每個元素的lambda,然後迭代它再次拿錢,再加上需要幾分鐘的時間才能找出後面發生的事情。有一個標準的做法。 – bereal

+0

@bereal:很確定這裏的迭代是懶惰的,它只迭代一次(除了初始排序)。 – Eric

4

我想最明顯的方式就是循環並把它們加起來。

>>> L=[('a',3),('b',4),('c',5),('a',2),('c',2),('b',1)] 
>>> import collections 
>>> d=collections.defaultdict(int) 
>>> for key,n in L: 
... d[key] += n 
... 
>>> sorted(d.items()) 
[('a', 5), ('b', 5), ('c', 7)] 
+1

可能更喜歡'collection.Counter',因爲它也免費提供'counter.most_common()'。 – bereal

0

您可以使用它的字典並添加重複鍵值,就像那樣。

dict = {} 
for i in L: 
    if i[0] in dict: 
     dict[i[0]] += i[1] 
    else: 
     dict[i[0]] = i[1] 
dict.items() 

輸出將是:[( '一個',5),( 'C',7),( 'B',5)]

0

可以嘗試以限定這樣的功能:

def sorting(L): 

    dit = {} 
    result = [] 
    for l in L : 
     dit[l[0]]= 0 


    for key , item in dit.items(): 
     for ll in L : 
       if key == ll[0] : 
        dit[key] += ll[1] 


    for key , item in dit.items(): 
     result.append((key , item)) 

    return sorted(result) 

,你會看到的結果是:

>>> sorting(L) 

[('a', 5), ('b', 5), ('c', 7)] 
相關問題