【问题标题】:Finding the most popular words in a list在列表中查找最流行的单词
【发布时间】:2011-07-11 12:28:11
【问题描述】:

我有一个单词列表:

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

【问题讨论】:

    标签: python string list words


    【解决方案1】:

    您可以为此使用counter

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

    它为元组提供了反转列。

    来自 cmets:collections.counter >=2.7,3.1。对于较低版本,您可以使用 the counter recipe

    【讨论】:

    • 仅在 Python 2.7+ 或 3.1+ 中。两者都没有被广泛使用,所以值得一提。
    • 如果您仍然使用较旧的 python 版本,您可以使用this recipe。我认为它提供了相同的界面。
    • 我的元组有反转列只是因为我对它进行排序更简单。 :) 我喜欢你的回答,因为它非常优雅,我不介意使用 Python 2.7。
    【解决方案2】:

    defaultdict 集合就是你要找的:

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

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

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

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

    from collections import Counter
    D = Counter(words)
    

    【讨论】:

      【解决方案3】:

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

      我觉得不错……

      你能做得更好吗?

      “更好”?如果它易于理解且高效,那还不够吗?

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

      【讨论】:

      • 我是一名 Python 学生,每天都在学习。欢迎任何提示,好的建议。
      • 顺便说一句:defaultdict 成就了我的一天!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多