Python Counter keys() 返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35071619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Counter keys() return values
提问by user3005486
I have a Counter that is already ordered by number of occurrences.
我有一个已经按出现次数排序的计数器。
counterlist = Counter({'they': 203, 'would': 138, 'your': 134,...}).
But when I do counterlist.keys()
the return list is:
但是当我这样做时counterlist.keys()
,返回列表是:
['wirespe', 'four', 'accus',...]
instead of
代替
['they', 'would', 'your',...].
Why?
为什么?
采纳答案by SirParselot
Counter()
Counter()
A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values.
Counter 是用于计算可散列对象的 dict 子类。它是一个无序集合,其中元素存储为字典键,它们的计数存储为字典值。
is an unordered dict so it does not keep the order in which you added them to the dict. If you want to keep them in order you will need to use an OrderedDict()
是一个无序的 dict,因此它不会保持您将它们添加到 dict 的顺序。如果你想让它们保持有序,你需要使用OrderedDict()
If you want an OrderedCounter()
then you could do this which I am pulling from herewhich has an explanation as to why it works.
如果你想要一个,OrderedCounter()
那么你可以这样做,我从这里拉出来,它解释了它为什么起作用。
from collections import *
class OrderedCounter(Counter, OrderedDict):
pass
counterlist = OrderedCounter({'would': 203, 'they': 138, 'your': 134})
print counterlist.keys()
回答by Tim Tisdall
While you entered the values in a dictionary in a particular order, a dict doesn't retain any sort of order. .keys()
on a dict returns in no particular order. There is an OrderedDict
that does retain order, but I don't know how that interacts with Counter
.
当您以特定顺序在字典中输入值时,字典不会保留任何顺序。 .keys()
在 dict 上没有特定的顺序返回。有一个OrderedDict
确实保留顺序,但我不知道它与Counter
.
EDIT:
编辑:
You may want to use Counter.most_common(). That will return a list of tuples which willbe in order.
您可能想要使用Counter.most_common()。这将返回记录其名单将在顺序。
回答by Bahaa
Another solution without creating an extra class is to take the set of items you have and sort them based on the counted keys. The code below is based on @user3005486:
另一种不创建额外类的解决方案是获取您拥有的一组项目,并根据计数的键对它们进行排序。以下代码基于@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']