查找给定字符串中使用的字符的最大频率
Finding max frequency of character used in a given string
在下面的代码中,我试图找出给定句子中最常用的字符。我使用了列表拆包,并且看到了解决此问题的不同方法。我的问题是,这是一个好方法吗?还是太复杂不干净?
输入
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
您可以使用 collections
包:
import collections
s = "This is a common interview question"
print(collections.Counter(s).most_common(1)[0])
在下面的代码中,我试图找出给定句子中最常用的字符。我使用了列表拆包,并且看到了解决此问题的不同方法。我的问题是,这是一个好方法吗?还是太复杂不干净?
输入
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
您可以使用 collections
包:
import collections
s = "This is a common interview question"
print(collections.Counter(s).most_common(1)[0])