我试图修改列出重复项的定义,以便它列出重复值的索引。另外,我希望列出所有重复项,这意味着a = [1,2,3,2,1,5,6,5,5,5]的结果将是重复索引= [3,4,7 ,8,9]这是定义:
def list_duplicates(seq):
seen = set()
seen_add = seen.add
# adds all elements it doesn't know yet to seen and all other to seen_twice
seen_twice = set( x for x in seq if x in seen or seen_add(x) )
# turn the set into a list (as requested)
return list( seen_twice )
a = [1,2,3,2,1,5,6,5,5,5]
list_duplicates(a) # yields [1, 2, 5]
最佳答案
a, seen, result = [1, 2, 3, 2, 1, 5, 6, 5, 5, 5], set(), []
for idx, item in enumerate(a):
if item not in seen:
seen.add(item) # First time seeing the element
else:
result.append(idx) # Already seen, add the index to the result
print result
# [3, 4, 7, 8, 9]
编辑:您可以在该函数中使用列表推导,就像这样
def list_duplicates(seq):
seen = set()
seen_add = seen.add
return [idx for idx,item in enumerate(seq) if item in seen or seen_add(item)]
print list_duplicates([1, 2, 3, 2, 1, 5, 6, 5, 5, 5])
# [3, 4, 7, 8, 9]
关于python - 使用Python在列表中列出重复值的索引,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23645433/