在 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


宝慕林4294392
浏览 122回答 1
1回答

慕哥9229398

您的代码中有逻辑错误(请参阅注释)。考虑使用计数器或默认字典:from collections import Counter, defaultdict#1frstdic = defaultdict(int)for nmb in ls:    frstdic[nmb] += 1#2frstdic = Counter(ls)在短序列上,计数器方法大约慢 4 倍,但对我来说似乎更优雅。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python