Python 的 计数器集合

等级 4163 次按键

这使用Counter来计算元素的出现次数。most_common()按降序返回元素和计数。

Python 代码

# 从collections模块导入Counter
1from collections import Counter
2
# 创建一个有重复单词的列表
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

Python 等级 4 的更多代码示例

← 返回 Python 打字练习