python - 获取字符串中出现次数最多的第一个字母

标签 python string python-3.x dictionary

我想得到一个字符串出现次数最多的第一个字母。

例如:

 "google" -> g  
 "azerty" -> a  
 "bbbaaa" -> b

我已经有了一个工作代码,使用 OrdererDict()避免自动键重新排列:

from collections import OrderedDict

sentence = "google"

d = OrderedDict()

for letter in sentence:
    if letter not in d.keys():
        d[letter] = sentence.count(letter)

print(max(d, key=d.get)) # g

但我正在寻找一种可能的单线或更优雅的解决方案(如果可能的话)。

注意: 我已经尝试使用 Counter()但它不起作用,因为 python 中的 dict 不记得插入键的顺序。

例如

from collections import Counter

sentence = "bbbaaa"

c = Counter(sentence)
print(c.most_common()[0][0]) # have 50% chances of printing 'a' rather than 'b'.

奖金问题:有人可以解释为什么 OrderedDict() 不是 python 中的默认字典行为吗?

最佳答案

collections.OrderedDict 的文档实际上有 a recipe for an OrderedCounter :

In [5]: from collections import Counter, OrderedDict

In [6]: class OrderedCounter(Counter, OrderedDict):
   ...:     pass
   ...:

In [7]: OrderedCounter("google").most_common()[0][0]
Out[7]: 'g'

关于python - 获取字符串中出现次数最多的第一个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39193241/

相关文章:

python - DASK 中的平面 map

python-3.x - Elastic Beanstalk CLI 部署 zip 错误

Python - 从包含类值的列表中打印

Java字符串数组初始化循环结构内外

python - 如果行以字母表中的任何字母开头,则打印行

java - 如何从字符串中取出数字?

python - 如何从目录中读取所有 .txt 文件

python - 素数python for循环

python - 在Python中从头开始构建:使用什么?

python - 在 tkinter python 中执行 ("after"脚本时如何处理无效的命令名称错误)