在下面的代码中,我试图在给定的句子中找到最常用的字符。我使用了列表解压缩,并且看到了解决此问题的不同方法。我的问题是,这是一个好方法吗?还是太复杂而不干净?
[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
在下面的代码中,我试图在给定的句子中找到最常用的字符。我使用了列表解压缩,并且看到了解决此问题的不同方法。我的问题是,这很好吗?
您可以使用collections
软件包:
import collections
s = "This is a common interview question"
print(collections.Counter(s).most_common(1)[0])