gpt4 book ai didi

python - 如何按频率和字母顺序对列表进行排序?

转载 作者:行者123 更新时间:2023-11-28 20:33:00 28 4
gpt4 key购买 nike

def count_words(s, n):
"""Return the n most frequently occuring words in s."""

# TODO: Count the number of occurences of each word in s

words = s.split()

counts = Counter(words)

# TODO: Sort the occurences in descending order (alphabetically in case of ties)

# TODO: Return the top n most frequent words.
return counts.most_common(n)

print count_words("betty bought a bit of butter but the butter was bitter", 3)

当前输出为:

[('butter', 2), ('a', 1), ('bitter', 1)]

但要求的是:

[('butter', 2), ('a', 1), ('betty', 1)]

因为频率相同,所以要按字母顺序排序。那么如何按字母顺序按频率对列表“计数”进行排序?

最佳答案

Python docs 所示

most_common([n])

Return a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered arbitrarily:

因此,无法保证以任何特定顺序列出的计数为 1 的顺序,因为底层结构是 dict

如果您希望结果按字母顺序排列,则需要进行更多处理。

from collections import Counter

c = Counter() #counter generating code

print sorted(c.most_common(), key=lambda i: (-i[1], i[0]))[:3]

这基本上首先通过获取所有结果。 .most_common() , 然后 sorts them按降序排列的第二个参数(单词频率),然后按升序排列的第一个参数(单词)。终于拿下了slice结果的前 3 个元素。

编辑:我意识到我没有正确排序,并且 itemgetter仅限于升序。

关于python - 如何按频率和字母顺序对列表进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51550654/

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