12

我有一个单词列表:

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

我想得到一个元组列表:

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

每个元组在哪里......

(number_of_occurrences, word)

该列表应按出现次数排序。

到目前为止我所做的:

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、优雅和高效的吗?你能做得更好吗?提前致谢。

4

3 回答 3

15

您可以为此使用计数器。

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)]

它为元组提供了反转列。

来自评论:collections.counter >=2.7,3.1。您可以将计数器配方用于较低版本。

于 2011-03-08T23:56:08.147 回答
6

defaultdict 集合是您要查找的内容:

from collections import defaultdict

D = defaultdict(int)
for word in words:
    D[word] += 1

这给了你一个字典,其中键是单词,值是频率。要获取您的(频率,单词)元组:

tuples = [(freq, word) for word,freq in D.iteritems()]

Counter如果使用 Python 2.7+/3.1+,您可以使用内置类执行第一步:

from collections import Counter
D = Counter(words)
于 2011-03-08T23:55:30.880 回答
2

它是 Pythonic、优雅和高效的吗?

对我来说看上去很好...

你能做得更好吗?

“更好的”?如果它是可以理解的和有效的,那还不够吗?

也许看看defaultdict使用它而不是 setdefault。

于 2011-03-08T23:52:46.707 回答