我想得到一个字符串出现次数最多的第一个字母。
例如:
"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/