Python数量统计Counter
from collections import Counter
if __name__ == "__main__":
xy = [
('z', 1),
('h', 1),
('a', 1),
('n', 1),
('g', 1),
('z', 1),
('h', 1)
]
c_xy = Counter(xy)
max_count = max(c_xy.keys(), key=c_xy.get)
print(max_count)
# 选取最多的那个点
max_count = c_xy.most_common(1)
print(max_count)
# 再选取前3多的点数
max_count = c_xy.most_common(3)
print(max_count)
输出:
('z', 1)
[(('z', 1), 2)]
[(('z', 1), 2), (('h', 1), 2), (('a', 1), 1)]
如果把xy的原始值修改为:
xy = [
'z',
'h',
'a',
'n',
'g',
'z',
'h'
]
再次运行代码,输出为:
z
[('z', 2)]
[('z', 2), ('h', 2), ('a', 1)]