python效率:计算dict中的键出现次数
试图获取python效率:计算dict中的键出现次数,python,Python,试图获取dict键的唯一值以及它们在列表中出现的次数。这很管用,但感觉很僵硬: 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} 有更好的方法吗?是的,有。使用: 是的,有。使用: 又短又甜
dict
键的唯一值以及它们在列表中出现的次数。这很管用,但感觉很僵硬:
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}
有更好的方法吗?是的,有。使用:
是的,有。使用:
又短又甜又短又甜
from collections import Counter
c = Counter(d['pid'] for d in a)
print(c)
# Counter({1: 3, 2: 2, 3: 1})