Find Index Of Item With Duplicates
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 o
Solution 1:
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):
defkey(item):
return something_hashable
for index, item inenumerate(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 itemsimport collections
somelist = list('ABRACADABRA')
seen = []
dups = collections.defaultdict(list)
for i, item inenumerate(somelist):
for j, orig inenumerate(seen):
if item == orig:
dups[j].append(i)
breakelse:
seen.append(item)
print([(seen[key], val) for key, val in dups.iteritems()])
yields
[('A', [3, 5, 7, 10]), ('B', [8]), ('R', [9])]
Solution 2:
Try this:
def get_duplicate_indexes(li):
retval = {}
for i, x in enumerate(li):
if x not in retval:
retval[x] = []
retval[x].append(i)
return retval
Solution 3:
>>>temp = {}>>>defprint_dupes(a):...for i,j inenumerate(a):... temp[j] = 0...for i,j inenumerate(a):... temp[j] += 1...for i,j inenumerate(a):...if temp[j] > 1:...print i...>>>print_dupes([1,1,1,2,2,2,3,3])
0
1
2
3
4
5
6
7
>>>print_dupes([1,1,1,2,2,2,3])
0
1
2
3
4
5
>>>print_dupes([1,1,1,2,3])
0
1
2
Post a Comment for "Find Index Of Item With Duplicates"