将数字计数为 Python 中的字符串
Counting Numbers as String in 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 倍,但对我来说似乎更优雅。
我是 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 倍,但对我来说似乎更优雅。