2016-12-03 80 views
8

考慮從一個映射初始化一個基本的計數器:的Python - 創建一個從映射計數器(),非整數值

dict_1 = {'a': 1, 'b': 2, 'c': 3} 
count_1 = Counter(dict_1) 
print count_1 

>>> Counter({'c': 3, 'b': 2, 'a': 1}) 

一切纔有意義。但Counter也允許我從包含鍵和值的非整數字典中進行初始化。例如,

dict_2 = {'a': 'apple', 'b': 'banana', 'c': 'cheese'} 
count_2 = Counter(dict_2) 
print count_2 

>>> Counter({'c': 'cheese', 'b': 'banana', 'a': 'apple'}) 

上面寫的代碼是Python 2.7,但我也在Python 3.5上測試了它,並得到了相同的結果。這似乎違反了計數器的最基本規則,其中「元素被存儲爲字典鍵並將其計數存儲爲字典值」。計數器是否應允許非整數值?它不應該拋出一個錯誤或什麼?什麼解釋了這種行爲?

回答

8

有一個計數器對象的值沒有任何限制,這是文件中明確提出:

Counter類本身是一本字典的子類,在其鍵和值沒有限制 。值爲打算爲數字 表示計數,但您可以在值字段中存儲任何

[重點礦山]

的一些Counter方法的行爲也以一般的情況下例如爲:描述

most_common()方法只需要這些值可訂購。

>>> count_2.most_common() 
[('c', 'cheese'), ('b', 'banana'), ('a', 'apple')] 
>>> count_2.most_common(2) 
[('c', 'cheese'), ('b', 'banana')] 

所以人們可以很容易碰到的問題在Python 3,如果你有unorderable類型作爲計數器對象的值:

>>> count_2['d'] = 2 
>>> count_2 
Counter({'c': 'cheese', 'a': 'apple', 'b': 'banana', 'd': 2}) 
>>> count_2.most_common() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "c:\Python34\lib\collections\__init__.py", line 492, in most_common 
    return sorted(self.items(), key=_itemgetter(1), reverse=True) 
TypeError: unorderable types: str() < int() 

因此,你通常要保留的值對象的實際數量並在值旨在爲非數字類型或更嚴格的非整數時使用vanilla字典。

+0

謝謝!這非常有幫助。 – GHH

+0

@GHH如果有幫助,你可以考慮接受答案 –