简体   繁体   English

按频率排序,而不是按字母顺序排列(在Python中)

[英]Ordering by frequency rather than alphabetically in a set (in Python)

I was looking at an example in the Python library where the total number of occurrences of a word in a list are ordered by their frequency count in a dictionary: 我正在看一个Python库中的示例,其中一个单词在列表中的出现总数按其在字典中的出现次数排序:

cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1

The output for cnt where the elements are listed in order of their frequency count: cnt的输出,其中元素按频率计数的顺序列出:

Counter({'blue': 3, 'red': 2, 'green': 1})

I want to make a set where the numerical frequencies aren't included, but the order the elements are listed is retained: 我想设置一个不包含数字频率的集合,但保留列出元素的顺序:

{'blue', 'red', 'green'}

However in my attempt to achieve this: 但是,在我尝试达到此目的时:

set(word for word, count in cnt.most_common(3))

I instead receive a set where the elements are ordered alphabetically instead of frequency count: 相反,我收到了一个集合,其中的元素按字母顺序而不是频率计数:

{'blue', 'green', 'red'}

Is it possible to order the set according to the frequency count? 是否可以根据频率计数订购设备?

Sets are a unordered collection of unique elements, as such ordering them has no meaning whatsoever. 集合是唯一元素的无序集合,因此对它们进行排序毫无意义。

You probably want a list, which is ordered. 你可能需要一个列表, 列表排序。 The following uses a list comprehension to construct a list of the keys. 下面使用列表推导来构造键的列表。

We can iterate over Counter.most_common() which returns a sequence of (key, value) tuples in order. 我们可以遍历Counter.most_common() ,它按顺序返回(key, value)元组序列。

from collections import Counter

c = Counter({'blue': 3, 'red': 2, 'green': 1})

keys = [key for key, val in c.most_common()]

print(keys)
# ['blue', 'red', 'green']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python中的频率分析-使用频率而不是频率来打印字母 - Frequency Analysis in Python -Print letters with frequency rather than numbers with frequency 按频率对计数器排序,然后在 Python 中按字母顺序排序 - Sort Counter by frequency, then alphabetically in Python 停止在字典中按字母顺序对字典进行Python排序 - Stop Python alphabetically ordering dicts within dicts 如何按数字而不是字母顺序对列表进行排序? - How can I sort a list numerically rather than alphabetically? 设置Snow Leopard使用python 2.5而不是2.6 - Set Snow Leopard to use python 2.5 rather than 2.6 Python-.txt文件中按频率和字母顺序排列有多少个单词? - Python - How many words are there in the .txt file in order by frequency and alphabetically? 在python中使用re.findall输出一组参数而不是每行的一组参数 - Using re.findall in python outputting one set of parameters rather than a set of parameters for each line Python:尝试按字母顺序对集合排序时出错 - Python:Error while trying to sort a set alphabetically 使用python设置xticks标签频率 - set xticks label frequency with python 外键中的字段按字母顺序排序 - ordering by a field in a foreign key alphabetically
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM