【问题标题】:Character frequency in a string (Python 3.9) [duplicate]字符串中的字符频率(Python 3.9)[重复]
【发布时间】:2025-12-25 22:20:09
【问题描述】:

如果不使用 if、while 或 for,如何计算字符串中的字符(字符频率)?

【问题讨论】:

  • 'aaabbc'.count('a')3
  • string = "abcdefa" string.count("a")
  • 在某种程度上,将需要 for/while 来迭代字符串。还有一个 if 语句来计算单个字符
  • 使用for char in set(your_string): print(your_string.count(char))遍历字符串中的所有唯一字符

标签: python python-3.x string python-3.9 charactercount


【解决方案1】:

你可以使用Counter,它返回一个以字符为键,频率为值的字典。

from collections import Counter
x = "abcdasbdd"
print(Counter(x))

输出

Counter({'d': 3, 'a': 2, 'b': 2, 'c': 1, 's': 1})

【讨论】: