from collections import Counter
a =["apple","banana","apple","cat","cat","cat","dog"]
b = Counter(a)print("type(b) = ",type(b))# type(b) = <class 'collections.Counter'>print("b = ", b)# b = Counter({'cat': 3, 'apple': 2, 'banana': 1, 'dog': 1})
定义方式:
Counter(可迭代对象)
Counter(字典)
from collections import Counter
a = Counter()# 空Counter
a = Counter('Hello World')# 统计每个字符出现次数
a = Counter([1,2,3,1,2])# 统计每个元素的出现次数# 利用该字典初始化每个元素(key)和出现次数(value)
a = Counter({'a':1,'b':2,'c':3})
a = Counter(a=1, b=2, c=3)
from collections import defaultdict
d = defaultdict(int)print(d['x'])# 0
d = defaultdict(list)print(d['x'])# []
d = defaultdict(set)print(d['x'])# set()
d = defaultdict(dict)print(d['x'])# {}
s =[('yellow',1),('blue',2),('yellow',3),('blue',4),('red',1)]
d = defaultdict(list)for k, v in s:
d[k].append(v)print(d)