一、使用字典 dict 统计
循环遍历出一个可迭代对象的元素,如果字典中没有该元素,那么就让该元素作为字典的键,并将该键赋值为1,如果存在则将该元素对应的值加1
lists = ['a','a','b',1,2,3,1]
count_dist = dict()
for i in lists:
if i in count_dist:
count_dist[i] += 1
else:
count_dist[i] = 1
print(count_dist)
# {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1}
二、使用 collections.defaultdict 统计
defaultdict(parameter) 接受一个类型参数,例如:int、float、str 等。
传递进来的类型参数,不是用来约束值的类型,更不是约束键的类型,而是当键不存在时,实现一种值的初始化。
defaultdict(int) – 初始化为0
defaultdict(float) – 初始化为0.0
defaultdict(str) – 初始化为’’
from collections import defaultdict
lists = ['a','a','b',1,2,3,1]
count_dict = defaultdict(int)
for i in lists:
count_dict[i] += 1
print(count_dict)
# defaultdict(<class 'int'>, {'a': 2, 'b': 1, 1: 2, 2: 1, 3: 1})
三、List count方法
统计List中每一个对象次数
test = ["aaa","bbb","aaa","aaa","ccc","ccc","ddd","aaa","ddd","eee","ddd"]
print(test.count("aaa"))
# 4
print(test.count("bbb"))
# 1
test_result = []
for i in test:
if i not in test_result:
test_result.append(i)
print(test_result)
for i in test_result:
print(f"{i}:{test.count(i)}")
'''
4
1
['aaa', 'bbb', 'ccc', 'ddd', 'eee']
aaa:4
bbb:1
ccc:2
ddd:3
eee:1
'''
四、使用集合(set)和列表(list)统计
先用 set 去重,然后循环把每一个元素和对应的次数 list.count(item) 组成元组。
lists = ['a','a','b',1,2,3,1]
count_set = set(lists)
print(count_set) # 集合去重
# {1, 2, 3, 'b', 'a'}
count_list = list()
for i in count_set:
count_list.append((i, lists.count(i)))
print(count_list)
# [(1, 2), (2, 1), (3, 1), ('b', 1), ('a', 2)]