2013-04-27 73 views
1

我使用Python集合庫打印出字符串中最常見的字符以及它重複的次數。使用Python修改collections.Counter的輸出

import collections 
results = collections.Counter("this is fun") 
listresults= results.most_common() 
print listresults 

這是我的結果是什麼:

[(' ', 2), ('i', 2), ('s', 2), ('f', 1), ('h', 1), ('n', 1), ('u', 1), ('t', 1)] 

這不是我想要的。我想要類似

[(2,"i") (2, " "),...] 

沒有人知道如何產生所需的結果嗎?

+0

你沒有得到這樣的輸出' Counter(「這很有趣」),是嗎? – Volatility 2013-04-27 01:43:53

+0

對不起,結果來自其他東西 – 2013-04-27 01:45:45

回答

4

你可以試試這個:

>>> from collections import Counter 
>>> results = Counter("this is fun") 
>>> r = results.most_common() 
>>> what_i_want = [(y, x) for x, y in r] 
>>> what_i_want 
[(2, ' '), (2, 'i'), (2, 's'), (1, 'f'), (1, 'h'), (1, 'n'), (1, 'u'), (1, 't')] 

我使用list comprehension,因爲列表理解往往比使用for條款更加高效和佔用少得多的空間。每下方的評論,不過,一個for條款看起來就像已經提出什麼jamylak:

>>> what_i_want = [] 
>>> for x, y in r: 
    what_i_want.append((y, x)) 
>>> what_i_want 
[(2, ' '), (2, 'i'), (2, 's'), (1, 'f'), (1, 'h'), (1, 'n'), (1, 'u'), (1, 't')] 
+0

我們可以把它寫成for循環plz例如:for x,y in r:... – 2013-04-27 01:49:52

+1

@TommyNgo'what_i_want = []''for x,y in r:what_i_want .append((y,x))'列表理解要好得多,儘管 – jamylak 2013-04-27 02:10:12

+0

@TommyNgo我用for循環更新了上面的答案,jamylak表示與列表理解等價。正如jamylak指出的那樣,列表理解將是創建您要查找的列表的最佳方式。 – 2013-04-27 13:40:27

0

另一個略少可讀性,但還是相當Python的方式:

import collections 
results = collections.Counter("this is fun") 
listresults= results.most_common() 
print listresults 
print zip(*reversed(zip(*listresults)))