Listing indices of duplicate values ​​in a list using Python

I am trying to change this definition that lists duplicate elements so that they display indices of duplicate values. In addition, I would like it to display ALL duplicates, which means that the result for a = [1,2,3,2,1,5,6,5,5,5,5] will be duplicate_indexes = [3,4, 7, 8,9] Here is the definition:

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] 
+6
source share
4 answers
 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] 

Edit: You can just use list comprehension in this function, e.g.

 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] 
+6
source

Accounting list to print duplicate index. It cuts the list to the selected index and returns the index value if the item is already in the sparse list

 a= [1, 2, 3, 2, 1, 5, 6, 5, 5, 5] result=[idx for idx, item in enumerate(a) if item in a[:idx]] print result #[3, 4, 7, 8, 9] 
+4
source
 def list_duplicates_index(seq): return [i for (i,x) in enumerate(a) if x in list_duplicates(a)] 
0
source
 def list_duplicates(seq): d = {} for i in seq: if i in d: d[i] += 1 else: d[i] = 1 dups = [] for i in d: if d[i] > 1: dups.append(i) lst = [] for i in dups: l = [] for index in range(len(seq)): if seq[index] == i: l.append(index) lst.append(l[1:]) new = [] for i in lst: for index in i: new.append(index) return new 
0
source

All Articles