如何获得OrderedDicts列表中重复元素的索引?

问题描述:

我有一个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' 

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