问题描述
我是python的新手。我一直在尝试计算1-9出现在列表中的次数,但是python不计算该数字,而是始终将其视为1,而没有为数字1-9的出现次数添加更多计数。有人可以帮助我理解原因吗?
#code
for 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
解决方法
您的代码中存在逻辑错误(请参见注释)。考虑使用计数器或默认字典:
from collections import Counter,defaultdict
#1
frstdic = defaultdict(int)
for nmb in ls:
frstdic[nmb] += 1
#2
frstdic = Counter(ls)
在短序列中,计数器方法要慢大约4倍,但对我来说似乎更优雅。