2013-05-20 67 views
0

平均重複的值,我有一個列表:轉換列表,字典和蟒蛇

list = [(a,1),(b,2),(a,3)] 

我想將其轉換爲一個字典,其中當有重複(如(a,1)(a,3)),它將會得到平均值,所以字典將只有1個關鍵字:值對,在這種情況下,將會是a:2

回答

3
from collections import defaultdict 
l = [('a',1),('b',2),('a',3)] 
d = defaultdict(list) 
for pair in l: 
    d[pair[0]].append(pair[1]) #add each number in to the list with under the correct key 
for (k,v) in d.items(): 
    d[k] = sum(d[k])/len(d[k]) #re-assign the value associated with key k as the sum of the elements in the list divided by its length 

所以

print(d) 
>>> defaultdict(<type 'list'>, {'a': 2, 'b': 2}) 

甚至更​​好,生產中端普通詞典:

from collections import defaultdict 
l = [('a',1),('b',2),('a',3)] 
temp_d = defaultdict(list) 
for pair in l: 
    temp_d[pair[0]].append(pair[1]) 
#CHANGES HERE 
final = dict((k,sum(v)/len(v)) for k,v in temp_d.items()) 
print(final) 
>>> 
{'a': 2, 'b': 2} 

請注意,如果你正在使用2.x的(你是,你會需要調整下面的強制float分割):

(k,sum(v)/float(len(v))) 

sum(d[k])/float(len(d[k])) 
+1

或者,只需在頂部添加'from __future__ import division'即可。 –

+0

@BurhanKhalid好點,謝謝:) – HennyH

+0

謝謝。我會試試看,因爲實際列表比我的示例3元素列表長很多。讓你知道它是如何去的 – gio888