在工作中我们经常要统计数字,字符,文件名出现的次数,常用的方法是字典,其实还有个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
网友评论