Python 的 Counter最常见

等级 4187 次按键

这使用Counter计算元素频率,并使用most_common()找到最常见的元素。

Python 代码

# 从collections导入Counter
1from collections import Counter
2
# 要分析的字符串
3text = "abracadabra"
# Counter统计每个字符出现的次数
4counter = Counter(text)
5
# 以dict形式按首次出现的顺序显示所有计数
6print(f"All: {dict(counter)}")
# 按次数取前3个;b和r都是2次,按首次出现的顺序排列
7print(f"Top 3: {counter.most_common(3)}")
# 像dict的键一样查找单个字符:'a'出现5次
8print(f"'a' count: {counter['a']}")

运行结果

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

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

这段代码中的符号

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

  • "× 8
  • (× 6
  • )× 6
  • '× 4
  • :× 3
  • {× 3
  • }× 3
  • =× 2
  • _× 1
  • .× 1

Python 等级 4 的更多代码示例

← 返回 Python 打字练习