2017-05-24 22 views
1

所以我有字典的這個名單:獲取所有值的平均值,如果某個鍵是一樣的

l = [{'COUNTRY': 'UK', 'CREDITS': '54'}, {'COUNTRY': 'PT', 'CREDITS': '100'}, {'COUNTRY': 'FR', 'CREDITS': '20'}, {'COUNTRY': 'UK', 'CREDITS': '30'}, {'COUNTRY': 'UK', 'CREDITS': '15'}, {'COUNTRY': 'PT', 'CREDITS': '35'}, {'COUNTRY': 'FR', 'CREDITS': '30'}] 

我需要得到每個國家的信用的平均值。輸出應該是這樣的:

l2 = {'UK': '102', 'PT': '67.5', 'FR': '25'} 

是否有任何簡單和容易的方法來實現呢?

回答

4

我會首先創建一個defaultdict以收集「COUNTRY」鍵下的整數列表中的值。

然後,我將創建一個字典的理解,執行平均:

l = [{'COUNTRY': 'UK', 'CREDITS': '54'}, {'COUNTRY': 'PT', 'CREDITS': '100'}, {'COUNTRY': 'FR', 'CREDITS': '20'}, {'COUNTRY': 'UK', 'CREDITS': '30'}, {'COUNTRY': 'UK', 'CREDITS': '15'}, 
{'COUNTRY': 'PT', 'CREDITS': '35'}, {'COUNTRY': 'FR', 'CREDITS': '30'}] 

import collections 

d = collections.defaultdict(list) 
for s in l: 
    d[s["COUNTRY"]].append(int(s["CREDITS"])) 

result = {k:sum(v)/len(v) for k,v in d.items()} 

print(result) 

結果:

{'UK': 33.0, 'PT': 67.5, 'FR': 25.0} 

注:1)您預期的結果是錯誤的,2)我轉換爲浮動,但你可以通過做把它作爲整數作爲字符串

result = {k:str(sum(v)//len(v)) for k,v in d.items()} 

這給:

{'PT': '67', 'FR': '25', 'UK': '33'} 
+0

真棒,謝謝!正是我想要的 – Cardo20

1

替代的解決方案使用itertools.groupby()itertools.tee()功能:

import itertools 

l = [{'COUNTRY': 'UK', 'CREDITS': '54'}, {'COUNTRY': 'PT', 'CREDITS': '100'}, {'COUNTRY': 'FR', 'CREDITS': '20'}, {'COUNTRY': 'UK', 'CREDITS': '30'}, {'COUNTRY': 'UK', 'CREDITS': '15'}, {'COUNTRY': 'PT', 'CREDITS': '35'}, {'COUNTRY': 'FR', 'CREDITS': '30'}] 
avgs = {} 

for k,g in itertools.groupby(sorted(l, key=lambda x: x['COUNTRY']), key=lambda x: x['COUNTRY']): 
    d1,d2 = itertools.tee(g) # copy `grouper` iterator to deal with "fresh" pointer 
    avgs[k] = sum(int(d['CREDITS']) for d in d1)/len(list(d2)) 

print(avgs) 

輸出:

{'UK': 33.0, 'FR': 25.0, 'PT': 67.5}