2017-02-07 81 views
2

我不能讓我的計數器進行排序/正常顯示Python的排序計數器

我的代碼是

with open('nonweb') as f: 
    for i in f: 
      entry.append(i.strip()) 
    counter=Counter(entry) 
print counter 

for z in counter: 
     print '%s : %d' % (z, counter[z]) 

計數器

Counter({'192.168.1.45 UDP 137': 2262, '192.168.1.85 UDP 137': 2262, '192.119.43.56 UDP 53': 78, '192.119.39.68 UDP 53': 78, '192.168.92.223 UDP 10111': 78, '192.168.1.13 UDP 137': 72, '192.167.80.106 TCP 8087': 48, '192.168.1.127 UDP 8083': 48, '192.168.1.129 UDP 8083': 44, '192.218.30.124 UDP 53': 32, '192.77.58.44 TCP 5282': 24, '192.168.1.13 UDP 138': 18, '192.168.1.69 UDP 138': 14, '192.168.1.85 UDP 138': 10, '192.168.1.57 UDP 138': 10, '192.168.1.33 UDP 138': 10, '192.168.1.45 UDP 138': 10, '192.168.1.92 UDP 138': 10, '192.168.1.97 UDP 138': 10, '192.168.1.79 UDP 138': 10, '192.168.1.60 UDP 138': 10, '192.168.1.32 UDP 138': 10, '192.168.1.18 UDP 138': 10, '192.168.1.58 UDP 138': 10, '192.168.1.95 UDP 138': 10, '192.168.1.19 UDP 138': 10, '192.168.1.143 UDP 138': 10, '192.168.1.138 UDP 138': 10, '192.168.1.99 UDP 138': 10, '192.168.1.139 UDP 138': 10, '192.168.1.96 UDP 138': 10, '192.168.1.140 UDP 138': 10, '192.168.1.137 UDP 138': 10, '192.168.1.59 UDP 138': 10, '192.171.70.154 UDP 53': 6, '216.163.251.236 TCP 42590': 2, '192.168.1.140 TCP 56230': 2}) 

,但是當我嘗試在一個像樣的格式來顯示它,它不會按照與計數器列表相同的順序進行打印。 (優選不半:結腸)

192.168.1.45 UDP 137 : 2262 
192.168.1.85 UDP 137 : 2262 
192.168.1.85 UDP 138 : 10 
192.168.1.57 UDP 138 : 10 
192.168.1.33 UDP 138 : 10 
192.168.1.45 UDP 138 : 10 
192.168.1.92 UDP 138 : 10 
192.168.1.129 UDP 8083 : 44 
192.168.1.97 UDP 138 : 10 
192.168.1.13 UDP 137 : 72 
192.168.1.79 UDP 138 : 10 
+1

計數器取決於字典取決於無序哈希表。 – Nils

+3

你在計數器的'repr'中看到的是計數器的內部字典,它沒有排序。如果你想按照排序順序排列內容,請嘗試'Counter.most_common' –

+0

你期望的順序是什麼?首先出現,最大發生次數,最小發生次數,關鍵? – AndreyF

回答

5

由於Counter被實現爲一個字典它並沒有真正有規程感。如果你想爲了在其元素手動循環,你將需要創建這樣的順序:

# reverse=True to get descending order 
for k, v in sorted(counter_obj.items(), key=lambda x: x[1], reverse=True): 
    print(k, v) 

或者乾脆遍歷由most_common方法返回的元組的列表,通過@tobias_k在評論中建議:

for k, v in c.most_common(): 
    print(k, v) 

而有趣的是most_common中幾乎確切的方式來實現:

def most_common(self, n=None): 
     '''List the n most common elements and their counts from the most 
     common to the least. If n is None, then list all element counts. 

     >>> Counter('abcdeabcdabcaba').most_common(3) 
     [('a', 5), ('b', 4), ('c', 3)] 

     ''' 
     # Emulate Bag.sortedByCount from Smalltalk 
     if n is None: 
      return sorted(self.items(), key=_itemgetter(1), reverse=True) 
     return _heapq.nlargest(n, self.items(), key=_itemgetter(1)) 
+2

或者只是'Counter.most_common'?也可以採取參數,例如前十名元素爲「most_common(10)」。 –

+0

@tobias_k確實,完全忘記了'most_common'返回有序的元組列表。謝謝 – DeepSpace

0

你有你的COUN什麼ter對象是一個dict。 的順序不是隨機的,但是:

鍵和值指的是這個非隨機的,不同的Python實現不同而不同,取決於插入和刪除的字典的歷史以任意順序遍歷。

你可以通過使用orderddict來解決這個問題。

有序字典就像普通字典一樣,但他們記得項目插入的順序。

2

使用counter.most_common()

for k,v in c.most_common(): 
    print(k,v)