2017-04-11 131 views
0

我有一個OrderedDicts的列表,我想獲取重複元素列表中的索引。從概念上講,這是一個有點像下面的例子中,其特點是int個清單:如何獲得OrderedDicts列表中重複元素的索引?

>>> def indices_of_list_element_duplicates(x): 
...  seen = set() 
...  for index, element in enumerate(x): 
...   if isinstance(element, list): 
...    element = tuple(element) 
...   if element not in seen: 
...    seen.add(element) 
...   else: 
...    yield index 
... 
>>> a = [1, 2, 3, 4, 5, 6, 1, 1, 9, 1] 
>>> indices = [index for index in indices_of_list_element_duplicates(a)] 
>>> indices 
[6, 7, 9] 

怎麼能這樣做的等價物的OrderedDicts名單中呢?當我嘗試這個功能在OrderedDicts,我遇到以下錯誤:

TypeError: unhashable type: 'OrderedDict' 

回答

1
from collections import OrderedDict 
# ... 
if isinstance(element, OrderedDict): # checking for type dict would be enough 
    element = tuple(element.items()) 
# ... 

此轉換字典元組可以反過來,是你的集合中的元素的元組。之前,您試圖向set添加一個對象,該對象不執行散列。

請注意,給定字典必須遞歸限制爲可哈希值類型。否則,你會遇到類似的問題。

from collections import OrderedDict 
d = OrderedDict(a=[1,2,3]) 
set().add(tuple(d.items())) 
TypeError: unhashable type: 'list' 
+0

啊,這是非常有益的。感謝關於遞歸檢查不可用的值類型的提示。 – BlandCorporation