Counter是Python内置的Collections库中提供的一种数据结构,利用它可以很方便的实现对各种数据的计数操作。
我们来看一个例子[每一步跟之前有联系,希望读者能一步一步跟着阅读]。
1.导入库,并通过一个list新建一个Counter
1
2
3
4
5
6
7
|
from collections import Counter
a_list = ['Yellow', 'Blue', 'Blue', 'Red', 'Red', 'Red']
a_list_c = Counter(a_list)
print("1. a_list_c的内容:")
print(a_list_c)
print("2. a_list里边有{}个Red" .format(str(c['Red'])))
|
输出结果为
1
2
3
|
1. a_list_c的内容:
Counter({'Red': 3, 'Blue': 2, 'Yellow': 1})
2. a_list里边有3个Red
|
2.查看Counter中最多的元素
1
2
3
|
a_list_most = a_list_c.most_common(1)
print("3. a_list里边最多的元素")
print(a_list_most)
|
输出结果为
1
2
|
3. a_list里边最多的元素
[('Red', 3)]
|
3. 向Counter中添加两个Orange
1
2
3
|
a_list_c['Orange'] +=2
print("4. 增加两个Orange以后a_list_c的内容:")
print(a_list_c)
|
输出结果为
1
2
|
4. 增加两个Orange以后a_list_c的内容:
Counter({'Red': 3, 'Blue': 2, 'Orange': 2, 'Yellow': 1})
|
4. 通过一个dict来新建另一个Counter
1
2
3
|
b_c = Counter({'Black': 4, 'Pink': 2})
print("5. 使用字典新建一个名为b_c的新Counter:")
print(b_c)
|
输出结果为
1
2
|
5. 使用字典新建一个名为b_c的新Counter:
Counter({'Black': 4, 'Pink': 2})
|
5. 最后将新的Counter和老的Counter相加
1
2
3
|
combined_c = a_list_c + b_c
print("6. 将a_list_c和b_c加起来的结果")
print(combined_c)
|
输出结果为
1
2
|
6. 将a_list_c和b_c加起来的结果
Counter({'Black': 4, 'Red': 3, 'Blue': 2, 'Orange': 2, 'Pink': 2, 'Yellow': 1})
|