选择列表中最常用的字符串,如果'n'字符串具有相同的频率计数,则按字母顺序比较每个字符串的第一个字母



我有一个列表:

Fruit_list = ['apples','oranges','peaches','peaches','watermelon','oranges','watermelon']

想要输出:

print(most_frequent(Fruit_list))

应该打印出">桔子">

我想找到列表中频率最高的字符串。最常见的三个项目是"桔子"、"豌豆"one_answers"耳朵"。但是,我想选择"范围">,因为字母中"o"在"p"one_answers"w"之前

from collections import Counter
fruits = ['apples','oranges','peaches','peaches','watermelon','oranges','watermelon']
counter = Counter(fruits)
sorted_fruits = sorted(counter.items(), key=lambda tpl: (-tpl[1], tpl[0]))
print(sorted_fruits[0][0])

输出:

oranges

我认为您正在寻找这样的函数:

def most_frequent(l):
return max(sorted(l, key=str.lower), key=l.count)
Fruit_list = ['apples','oranges','peaches','peaches','watermelon','oranges','watermelon']
print(most_frequent(Fruit_list))  # outputs "oranges"

如果您不想使用CCD_ 1。

澄清:

  1. sorted(l, key=str.lower)按字典顺序对列表l进行排序。

  2. max(<>, key=l.count)获取排序列表的模式。

您尝试过以下操作吗:

from collections import Counter
words = ['apples','oranges','peaches','peaches','watermelon','oranges','watermelon']
most_common_words= [word for word, word_count in Counter(words).most_common(3)]
most_common_words
from collections import Counter
Fruit_list = ['apples','zranges','peaches','peaches','watermelon','zranges','watermelon']
max_counter = 0
min_ret = "z"
my_dict = dict(Counter(Fruit_list))

for items in my_dict.keys():
if my_dict[items] > max_counter:
max_counter = my_dict[items]
min_ret = items
if my_dict[items] == max_counter:
if items < min_ret:
min_ret = items
print(min_ret)

~

最新更新