Python 的 计数器集合
等级 4163 次按键
这使用Counter来计算元素的出现次数。most_common()按降序返回元素和计数。
Python 代码
# 从collections模块导入Counter1from collections import Counter2 # 创建一个有重复单词的列表3words = ["apple", "banana", "apple", "cherry", "banana", "apple"]# Counter计算每个元素的出现次数4count = Counter(words)5 # 打印显示所有计数的Counter对象6print(count)# 获取2个最常见的元素及其计数7print(count.most_common(2))运行结果
Counter({'apple': 3, 'banana': 2, 'cherry': 1})
[('apple', 3), ('banana', 2)]可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 Python 代码中需要输入的符号及其出现次数。
"× 12,× 5(× 4)× 4=× 2_× 1.× 1[× 1]× 1