我是蟒蛇的新手。我一直在尝试计算 1-9 在列表中出现的次数,但 python 不会计算该数字并始终将其视为 1,而不会为数字 1-9 的出现次数添加更多计数。有谁可以帮助我理解为什么?#codefor nmb in ls: if nmb is not ls: frstdic[nmb] = 1 else: frstdic[nmb] = frstdic[nmb] + 1 print (frstdic) #return{'1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1, '7': 1, '8': 1, '9': 1}# nmb is a string
1 回答
![?](http://img1.sycdn.imooc.com/533e4c2300012ab002200220-100-100.jpg)
慕哥9229398
TA贡献1877条经验 获得超6个赞
您的代码中有逻辑错误(请参阅注释)。考虑使用计数器或默认字典:
from collections import Counter, defaultdict
#1
frstdic = defaultdict(int)
for nmb in ls:
frstdic[nmb] += 1
#2
frstdic = Counter(ls)
在短序列上,计数器方法大约慢 4 倍,但对我来说似乎更优雅。
添加回答
举报
0/150
提交
取消