试图获取dict
密钥的唯一值以及它们出现的次数list
.这有效,但感觉很笨拙:
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}
有更好的方法吗?
就在这里.用途collections.Counter
:
from collections import Counter c = Counter(d['pid'] for d in a) print(c) # Counter({1: 3, 2: 2, 3: 1})