美文网首页
python3 统计字符数字出现次数

python3 统计字符数字出现次数

作者: 打五笔的程序员 | 来源:发表于2020-10-07 22:46 被阅读0次
在工作中我们经常要统计数字,字符,文件名出现的次数,常用的方法是字典,其实还有个Counter可以使用

1.字典方法

L = ["a","b","c","d","e","f","g","j","o","a","c","d","e","b","e","g","a","a","c","d"]
d = {}

for i in L:
    if i in d:
        d[i] += 1
    else:
        d[i] = 1
print(d)
结果

2.使用collections里面的Counter

from collections import Counter

L = ["a","b","c","d","e","f","g","j","o","a","c","d","e","b","e","g","a","a","c","d"]
print(dict(Counter(L)))
使用Counter结果

当然还有很多可以统计比如某个目录下的所有目录里有的文件,有多少个名称是一样,也可以统计出来,像统计单词个数之类的都可以使用,不过使用前要先生成list

相关文章

网友评论

      本文标题:python3 统计字符数字出现次数

      本文链接:https://www.haomeiwen.com/subject/ycwqpktx.html