本文介绍了在列表中查找最受欢迎的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单词列表:

words = ['all', 'awesome', 'all', 'yeah', 'bye', 'all', 'yeah']

我想获取一个元组列表:

And I want to get a list of tuples:

[(3, 'all'), (2, 'yeah'), (1, 'bye'), (1, 'awesome')]

每个元组在哪里...

where each tuple is...

(number_of_occurrences, word)

该列表应按出现次数进行排序.

The list should be sorted by the number of occurrences.

到目前为止我所做的:

def popularWords(words):
    dic = {}
    for word in words:
        dic.setdefault(word, 0)
        dic[word] += 1
    wordsList = [(dic.get(w), w) for w in dic]
    wordsList.sort(reverse = True)
    return wordsList

问题是...

它是Pythonic,优雅且高效的吗?你能做得更好吗?预先感谢.

Is it Pythonic, elegant and efficient?Are you able to do it better?Thanks in advance.

推荐答案

您可以使用计数器.

import collections
words = ['all', 'awesome', 'all', 'yeah', 'bye', 'all', 'yeah']
counter = collections.Counter(words)
print(counter.most_common())
>>> [('all', 3), ('yeah', 2), ('bye', 1), ('awesome', 1)]

它使元组具有反向列.

It gives the tuple with reversed columns.

从注释中:collections.counter为> = 2.7,3.1.您可以将计数器食谱用于较低版本.

From the comments: collections.counter is >=2.7,3.1. You can use the counter recipe for lower versions.

这篇关于在列表中查找最受欢迎的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-18 17:32