gpt4 book ai didi

python - 查找列表中最流行的词

转载 作者:太空狗 更新时间:2023-10-29 19:36:13 29 4
gpt4 key购买 nike

我有一个单词列表:

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

最佳答案

您可以使用 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)]

它给出了带有反转列的元组。

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

关于python - 查找列表中最流行的词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5239781/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com