您只能使用不可變的字典鍵的值。 set()
值是可變的,所以這些不能被使用:
>>> lst = ['A', 'B', 'C', 'A', 'B']
>>> {{x}: y for x, y in enumerate(lst)}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <dictcomp>
TypeError: unhashable type: 'set'
frozenset()
values使用代替:
{frozenset([x]): y for x, y in enumerate(lst)}
演示:
>>> lst = ['A', 'B', 'C', 'A', 'B']
>>> {frozenset([x]): y for x, y in enumerate(lst)}
{frozenset([4]): 'B', frozenset([2]): 'C', frozenset([3]): 'A', frozenset([0]): 'A', frozenset([1]): 'B'}
字典鍵必須是可哈希;看到映射類型的文檔:
A dictionary’s keys are almost arbitrary values. Values that are not hashable , that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.
和hashable entry in the Python glossary:
An object is hashable
if it has a hash value which never changes during its lifetime (it needs a __hash__()
method), and can be compared to other objects (it needs an __eq__()
or __cmp__()
method). Hashable objects which compare equal must have the same hash value.
由於set
值是可變的,它們失敗可哈希標準;任何兩個現在比較相等的集合,可以稍後改變爲不再相等,因此它們的哈希值也需要改變。由於字典和集合均依賴散列值而非更改,因此可變容器不能用作字典鍵。 (而不是鍵)不限於可哈希對象。
如果你想創建設置值而是使用一個循環:
dct = {}
for x, y in enumerate(lst):
dct.setdefault(y, set()).add(x)
或使用collections.defaultdict
對象,而不是和避免.setdefault()
電話:
from collections import defaultdict
dct = defaultdict(set)
for x, y in enumerate(lst):
dct[y].add(x)
演示:
>>> lst = ['A', 'B', 'C', 'A', 'B']
>>> dct = {}
>>> for x, y in enumerate(lst):
... dct.setdefault(y, set()).add(x)
...
>>> dct
{'A': set([0, 3]), 'C': set([2]), 'B': set([1, 4])}
>>> from collections import defaultdict
>>> dct = defaultdict(set)
>>> for x, y in enumerate(lst):
... dct[y].add(x)
...
>>> dct
defaultdict(<type 'set'>, {'A': set([0, 3]), 'C': set([2]), 'B': set([1, 4])})
當你聲明某些東西不是我的rk,*包含錯誤消息*。在這種情況下,我很容易猜出哪裏出了問題,但是你不能指望每個人都一直這樣猜測。 –
你不想在代碼中使用像'list'這樣的名字;它掩蓋了內置的類型。改用'lst'或'somelist'或其他。 –