gpt4 book ai didi

python - python 中的键错误

转载 作者:行者123 更新时间:2023-12-01 07:24:25 25 4
gpt4 key购买 nike

我试图计算列表中每个字符串重复的次数,但它一直给我 KeyError:

def gono(l):
f={}
for h in l:
if(f.get(f[h])):
f[h] += 1
else:
f[h]=1
return f
Error content :
KeyError Traceback (most recent call last)
<ipython-input-68-e02904625299> in <module>
23 f[h]=1
24 return f
---> 25 v=gono(h)
26 v
27

<ipython-input-68-e02904625299> in gono(l)
18 f={}
19 for h in l:
---> 20 if(f.get(f[h])):
21 f[h] += 1
22 else:

KeyError: 'CLOSED'

列表是:['关闭', '待付款', '完全的', '关闭', '完全的', '完全的', '完全的', '加工', '待付款', “PENDING_PAYMENT”]

最佳答案

只需使用 Counter :

from collections import Counter
def gono(l):
return Counter(l)

结果示例:

>>> gono(['CLOSED', 'PENDING_PAYMENT', 'COMPLETE', 'CLOSED', 'COMPLETE', 'COMPLETE', 'COMPLETE', 'PROCESSING', 'PENDING_PAYMENT', 'PENDING_PAYMENT'])
Counter({'COMPLETE': 4, 'PENDING_PAYMENT': 3, 'CLOSED': 2, 'PROCESSING': 1})

关于python - python 中的键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57529881/

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