Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Counter keys()返回值_Python_Counter - Fatal编程技术网

Python Counter keys()返回值

Python Counter keys()返回值,python,counter,Python,Counter,我有一个计数器,它已按出现次数排序 counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...}). 但是当我执行counterlist.keys()时,返回列表是: ['wirespe', 'four', 'accus',...] 而不是 ['they', 'would', 'your',...]. 为什么?计数器() 计数器是用于计算可散列对象的dict子类。它是一个无序集合,其中元素存储为字典键,其计数存储为字典

我有一个计数器,它已按出现次数排序

counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...}).
但是当我执行
counterlist.keys()
时,返回列表是:

['wirespe', 'four', 'accus',...]
而不是

['they', 'would', 'your',...].
为什么?

计数器()

计数器是用于计算可散列对象的dict子类。它是一个无序集合,其中元素存储为字典键,其计数存储为字典值

是一个无序的dict,因此它不会保持您将它们添加到dict中的顺序。如果您希望保持它们的顺序,则需要使用

如果您想要一个
OrderedCounter()
,那么您可以这样做,我从中得到了一个解释,解释了它为什么工作

from collections import *

class OrderedCounter(Counter, OrderedDict):
    pass

counterlist = OrderedCounter({'would': 203, 'they': 138, 'your': 134})

print counterlist.keys()

当您在字典中按特定顺序输入值时,dict不会保留任何顺序.keys()不按特定顺序返回。有一个
OrderedDict
可以保持顺序,但我不知道它如何与
计数器进行交互

编辑:


您可能想使用。这将返回一个元组列表,有序。

另一个不创建额外类的解决方案是获取您拥有的项集,并根据计数的键对它们进行排序。以下代码基于@user3005486:

import collections

#if this is your list    
list_to_be_sorted = ['they', 'would', 'they', ...]
#then counterlist = {'would': 203, 'they': 138, 'your': 134}
counterlist = collections.Counter(list_to_be_sorted)
#if you sort this list ascendingly you get ['would', 'would', ..., 'they', 'they', ...etc.]
sorted_words = sorted(counterlist, key: lambda x:-counterlist[x])
distinct_words_from_list = set(list_to_be_sorted)
sorted_distinct_list = sorted(distinct_words_from_list, key: lambda x:-counterlist[x])
#then sorted_distinct_list = ['would', 'they', 'your']

问题是从2016年开始的,同时Python中的词典保证插入顺序的保留符合

从:

在版本3.7中更改:作为子类,继承了记住插入顺序的功能。计数器对象上的数学操作也保持顺序。结果的顺序取决于在左操作数中首次遇到元素的时间,然后是在右操作数中遇到的顺序

因此,对于Python>=3.7

counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...})
counterlist.keys()                                                                                                                                           
# Out: dict_keys(['they', 'would', 'your'])

另请参见:

如果
钥匙
给您的钥匙不在
计数器中
。。。您在错误的字典上调用了它。python字典没有排序
{…}
是一本字典。我有这样的印象,OP偶然得到了一个有序的打印输出,但是在调用
.keys()
后,结果不同。不幸的是,如上所述,这些示例不共享一个密钥,因此无法确定您的意思是希望密钥按其计数顺序排列吗?使用
counterlist.most_common()
进行排序(或
[e[0]用于counterlist.most_common()]
.Ah…
-counterlist[x]
反向排序)。这是旧的,因为Python默认有dict order。Python 3.6及更高版本有dict order。下面是一个很好的详细说明。这也不能真正解决OP的问题,因为它只保证插入内容的顺序,所以不会按大小顺序返回它们