2012-06-15 43 views
3

我現在有的代碼:如何將一個Counter對象轉換爲一個可用的對列表?

from collections import Counter 
c=Counter(list_of_values) 

回報:

Counter({'5': 5, '2': 4, '1': 2, '3': 2}) 

我想通過項目,不出現的次數進行排序這個列表爲數字(/字母)順序。我怎麼能轉換到這一點對,如清單:

[['5',5],['2',4],['1',2],['3',2]] 

注:如果我使用c.items(),我得到:dict_items([( '1',2),( '3', 2),('2',4),('5',5)]) 這不會幫助我...

在此先感謝!

+2

那如何幫不了你?你不能簡單地排序'c.items()'的結果嗎? – kindall

回答

8

嗯...

3>> list(collections.Counter(('5', '5', '4', '5')).items()) 
[('5', 3), ('4', 1)] 
+0

OP希望他們按鍵排序。 – PaulMcG

+0

@保羅:這是最簡單的部分。 (不是說這個*中的任何一個都是特別困難的......) –

+0

是的,我要問,哪一個很困難? – PaulMcG

1

如果要通過項目來排序數字小/字母升序:

l = [] 
for key in sorted(c.iterkeys()): 
    l.append([key, c[key]]) 
0

你可以用sorted()

>>> c 
Counter({'5': 5, '2': 4, '1': 2, '3': 2}) 
>>> sorted(c.iteritems()) 
[('1', 2), ('2', 4), ('3', 2), ('5', 5)] 
+1

更好地在Python 2中使用'sorted(c.iteritems())'。 – martineau

-1
>>>RandList = np.random.randint(0, 10, (25)) 
>>>print Counter(RandList) 

輸出類似...

Counter({1: 5, 2: 4, 6: 4, 7: 3, 0: 2, 3: 2, 4: 2, 5: 2, 9: 1}) 

而與此...

>>>thislist = Counter(RandList) 
>>>thislist = thislist.most_common() 
>>>print thislist 
[(1, 5), (2, 4), (6, 4), (7, 3), (0, 2), (3, 2), (4, 2), (5, 2), (9, 1)] 
>>>print thislist[0][0], thislist[0][1] 
1 5 
相關問題