【笔记】统计每一个元素的数量

记录一个Python小技巧:用于统计每一个元素的数量

利用字典方法,get

语法

get()方法语法:

dict.get(key, default)

参数

  • key -- 字典中要查找的键。
  • default -- 如果指定键的值不存在时,返回该默认值。
# 统计每一个元素的数量
a = ["a","b","c","a","a","b","b","c","d","a","d","e"]
dic = {}
for i in a:
    dic[i]= dic.get(i , 0)+1
print(dic)

通常我们用的Counter其实也是继承字典写的;

from collections import Counter
a = [1,2,3,1,2,3,1,1,1,2,3,4,2,12,3,]

count = Counter()
for i in a:
    count[i] +=1

print(count)

猜你喜欢

转载自blog.csdn.net/Finks_Chen/article/details/105224447
今日推荐