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

2024-06-25 23:43:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个清单:

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

要输出:

print(most_frequent(Fruit_list))

应该打印出“橙子

我想找到列表中最频繁的字符串。最常见的3种食物是“橘子”、“桃子”、“梨”。但是,我想选择'oranges',因为字母表中'o'在'p'和'w'之前


Tags: 字符串most列表list食物printfruitoranges
3条回答

您是否尝试了以下操作:

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

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"

。。。如果您不想使用Counter。你知道吗

澄清:

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

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

相关问题 更多 >