[英]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.