Finding the most popular words in a list

前端 未结 3 1101
我寻月下人不归
我寻月下人不归 2021-02-05 22:32

I have a list of words:

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

And I want to get a list of tuples:

3条回答
  •  别跟我提以往
    2021-02-05 23:22

    The defaultdict collection is what you are looking for:

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

    That gives you a dict where keys are words and values are frequencies. To get to your (frequency, word) tuples:

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

    If using Python 2.7+/3.1+, you can do the first step with a builtin Counter class:

    from collections import Counter
    D = Counter(words)
    

提交回复
热议问题