2017-01-19 62 views
1

嘗試獲取dict密鑰的唯一值以及它們出現在list中的次數。這工作,但感覺janky:python效率:在字典中計算關鍵事件

a = [ {'pid': 1 }, {'pid': 1}, {'pid': 1}, {'pid': 2}, {'pid': 2}, {'pid': 3} ] 
b = { x['pid']: len([f for f in a if f['pid'] == x['pid']]) for x in a } 
b 

產量:

{1: 3, 2: 2, 3: 1} 

是否有更好的辦法嗎?

回答

6

是的,有。使用collections.Counter

from collections import Counter 

c = Counter(d['pid'] for d in a) 
print(c) 
# Counter({1: 3, 2: 2, 3: 1}) 
+0

短而甜 – Wells