Find index of item with duplicates
list, python
Solution
If the items in the list are hashable, you could use them as keys in a dict:
import collections
somelist = list('ABRACADABRA')
dups = collections.defaultdict(list)
for index, item in enumerate(somelist):
dups[item].append(index)
print(dups)
yields
defaultdict(<type 'list'>, {'A': [0, 3, 5, 7, 10], 'R': [2, 9], 'B': [1, 8], 'C': [4], 'D': [6]})
If the items are not hashable (such as a list), then the next best solution is to define a `key` function (if possible) which maps each item to a unique hashable object (such as a tuple):
def key(item):
return something_hashable
for index, item in enumerate(somelist):
dups[key(item)].append(index)
If no such `key` can be found, you'd have to store the seen items in a list, and test for duplicates by testing equality with each item in the list of seen objects. This is O(n**2).
# Don't use this unless somelist contains unhashable items
import collections
somelist = list('ABRACADABRA')
seen = []
dups = collections.defaultdict(list)
for i, item in enumerate(somelist):
for j, orig in enumerate(seen):
if item == orig:
dups[j].append(i)
break
else:
seen.append(item)
print([(seen[key], val) for key, val in dups.iteritems()])
yields
[('A', [3, 5, 7, 10]), ('B', [8]), ('R', [9])]
Problem
I have a list which has many duplicates in, how can I find the index of all the duplicates in the array. So basically I search for a data item and if it has duplicates. It prints out the indexes of where the item is found, including where the duplicates are