我是编程新手,这个问题可能很乏味。
假设我有一个list=['stack',....,'overflow']
和一个len(list)=n
。我想在列表中找到最常见的起始字母。即“我”。我尝试使用.startswith()
和.most_common([n])
,但没有得到结果。什么是好的方法?
答案 0 :(得分:1)
您可以使用collections.Counter
:
Counter(x[0] for x in lst).most_common()[0]
其中lst
是您的列表。 (请注意,我已将您的列表重命名为lst
)
示例:
from collections import Counter
lst = ['stack', 'in', 'over', 'for', 'overflow']
print(Counter(x[0] for x in lst).most_common()[0])
# ('o', 2)
答案 1 :(得分:1)
您可以在下面使用实现。我已经解释了注释中的所有步骤。
words = ["a","b","a","d","d"] # it is your list
frequencies = [(letter, words.count(letter)) for letter in set(words)] #we are taking letters and their counts which is a tuple in a list
most_frequent_letter = sorted(frequencies, key=lambda x: x[1],reverse=True)[0] # and we are doing a stable sort for listing most frequent letters first.
print(most_frequent_letter)