如何解决在Python中将数字计数为字符串
我是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倍,但对我来说似乎更优雅。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。