Python 的 Counter使用

等级 5125 次按键

这使用Counter计算字符出现次数。Counter提供了像most_common()这样方便的频率分析方法。

Python 代码

# 从collections模块导入Counter
1from collections import Counter
2
# 定义要分析的字符串
3text = "abracadabra"
# Counter自动计算每个字符的出现次数
# 创建类似dict的对象:{'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
4counts = Counter(text)
# most_common(n)以(元素, 计数)元组返回n个最频繁的元素
5print(counts.most_common(3))
# 将Counter转换为普通dict以显示
6print(dict(counts))

运行结果

[('a', 5), ('b', 2), ('r', 2)]
{'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 Python 代码中需要输入的符号及其出现次数。

  • (× 5
  • )× 5
  • "× 2
  • =× 2
  • _× 1
  • .× 1

Python 等级 5 的更多代码示例

← 返回 Python 打字练习