查找给定字符串中使用的字符的最大频率

问题描述 投票:0回答:1

在下面的代码中,我试图在给定的句子中找到最常用的字符。我使用了列表解压缩,并且看到了解决此问题的不同方法。我的问题是,这是一个好方法吗?还是太复杂而不干净?

[Input] >>

sentence = "This is a common interview question"
characters = list(
    {
        (char, sentence.count(char))
        for char in sentence if char != ' '
    }
)

characters.sort(
    key=lambda char: char[1],
    reverse=True
)

print(f"'{characters[0][0]}' is repeated {characters[0][1]} times")

[输出

] >>
'i' is repeated 5 times

在下面的代码中,我试图在给定的句子中找到最常用的字符。我使用了列表解压缩,并且看到了解决此问题的不同方法。我的问题是,这很好吗?

python lambda iterable-unpacking
1个回答
0
投票

您可以使用collections软件包:

import collections
s = "This is a common interview question"
print(collections.Counter(s).most_common(1)[0])
© www.soinside.com 2019 - 2024. All rights reserved.