简介
之前都没很在意过collections
这个模块,以为有很多复杂的功能,所以只考虑了defaultdict
一个用法。没想到今天做力扣的时候,看官方解答中Counter
也是属于collections
模块,这么看这个还是很不错的。
写个总结,以备以后快速检索。
PS:发现这个博客写的很详细啊,有不懂的可以去看看:Python常用数据结构之collections模块
总结
Counter
从名称就能看出来,Counter
是计数器,可以对字符串,列表,字典实现计数功能。
示例程序:
from collections import Counter
str = "abcbcaccbbad"
li = ["a","b","c","a","b","b"]
d = {"1":3, "3":2, "17":2}
#Counter获取各元素的个数,返回字典
print ("Counter(s):", Counter(str))
print ("Counter(li):", Counter(li))
print ("Counter(d):", Counter(d))
输出为:
>>>> Counter(s): Counter({'b': 4, 'c': 4, 'a': 3, 'd': 1})
>>>> Counter(li): Counter({'b': 3, 'a': 2, 'c': 1})
>>>> Counter(d): Counter({'1': 3, '3': 2, '17': 2})
defaultdict
from collections import defaultdict
dict1 = defaultdict(int)
dict2 = defaultdict(set)
dict3 = defaultdict(str)
dict4 = defaultdict(list)
dict1[2] ='two'
print(dict1[1])
print(dict2[1])
print(dict3[1])
print(dict4[1])