gpt4 book ai didi

python 效率: counting key occurrences in dict

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:01 25 4
gpt4 key购买 nike

尝试获取 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})

关于 python 效率: counting key occurrences in dict,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41751957/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com