2016-01-28 31 views
0

我有一個計數器已經按出現次數排序。Python計數器鍵()返回值

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

但是當我做counterlist.keys()返回列表是:中

['wirespe', 'four', 'accus',...] 

代替

['they', 'would', 'your',...]. 

爲什麼?

+0

如果'keys'給你的鍵不在你的'Counter'中......你把它叫做錯誤的字典。 – timgeb

+0

python字典不是訂購的。 '{...}'是一本字典。 – Aprillion

+0

我給人的印象是,OP偶然得到了一個有序的打印輸出,但後來調用'.keys()',結果就不一樣了。不幸的是,正如上面指出的那樣,這些例子並不共享單個密鑰,所以不可能告訴 – Pynchia

回答

8

Counter()

A計數器是用於計數可哈希對象的字典子類。它是一個無序的集合,元素作爲字典鍵存儲,並且它們的計數存儲爲字典值。

是一個無序的字典,所以它不會保留您將它們添加到字典中的順序。如果你想保持他們爲了你需要如果你想要一個OrderedCounter(),那麼你可以做到這一點,我是從here它有一個解釋,爲什麼它的作品拉到使用OrderedDict()

from collections import * 

class OrderedCounter(Counter, OrderedDict): 
    pass 

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

print counterlist.keys() 
2

當您按特定順序在字典中輸入值時,字典不保留任何順序。字典上的.keys()以特定順序返回。有一個OrderedDict確實保持順序,但我不知道如何與Counter進行交互。

編輯:

您可能需要使用Counter.most_common()。這將返回一個元組列表,其中按順序排列。

0

另一種不創建額外類的解決方案是獲取您擁有的一組物品,並根據計數的鍵對它們進行分類。下面的代碼是基於@ 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']