List indexes of duplicate values in a list with Python
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 that function, like this
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]
How to fix the index of duplicate in a list
"Return Value from List index()
The index() method returns the index of the given element in the list.
If the element is not found, a ValueError exception is raised.
Note: The index() method only returns the first occurrence of the matching element.(https://www.programiz.com/python-programming/methods/list/index)"
https://www.geeksforgeeks.org/enumerate-in-python/
import copy
a = [1,2,2,6,7]
b = copy.deepcopy(a)
b.sort(reverse = True)
position = []
arr=[]
for i in enumerate(b):# a[7, 6, 2, 2, 1]
'''
ind val
(0, 7)
(1, 6)
(2, 2)
(3, 2)
(4, 1)
'''
arr.append(i[0])
position=arr[::-1]
'''
a= [1,2,2,6,7]
ind=[0,1,2,3,4]
reverse ...
b= [7,6,2,2,1]
ind= [0,1,2,3,4]
reverse ...
resul=[4,3,2,1]
'''
print(position)
Finding indices of duplicate items in Python
If you already have a numpy array, you can use np.unique
and use the return_inverse
flag. Use the inverse array to find all positions where count of unique elements exceeds 1, and find their indices.
import numpy as np
arr = np.array([[10,10],[3,6],[2,4],[10,10],[0,0],[2,4]])
vals, inverse, count = np.unique(arr,
return_inverse=True,
return_counts=True,
axis=0)
out = np.where(count[inverse] > 1)[0] #find all indices where counts > 1
print(out) #array([0, 2, 3, 5], dtype=int64)
Using .index() with a list that has repeated elements
Use enumerate
.
>>> top = [1, 3, 7, 8, 3, -3, 3, 0]
>>> hits = (i for i,value in enumerate(top) if value == 3)
This is a generator that will yield all indices i
where top[i] == 3
.
>>> for i in hits:
... print(i)
...
1
4
6
how to index duplicates in a list?
You can use a dictionary where the key is an item from your id list and the value is the count. Then when you find a new id, append the id to the output list. However, if the id is already in the dictionary, then increment the count and append the id along with that count to the output list. Finally, return the list. Here is an example code in python:
ids = ["a", "b", "c", "a", "a", "d", "c"]
output_ids = []
id_count = {}
# iterate through ids
for item in ids:
# if it's a new id
if item not in id_count:
# add it to dictionary
id_count[item] = 0
# add it to the output as is
output_ids.append(item)
# if it's not new
else:
# increment its count
id_count[item] += 1
# add it to the output along with its count
output_ids.append(f"{item}_{id_count[item]}")
print(output_ids) # ['a', 'b', 'c', 'a_1', 'a_2', 'd', 'c_1']
Related Topics
How to Make Image/Images Disappear in Pygame
How to Create Animated Sprites Using Sprite Sheets in Pygame
Separation of Business Logic and Data Access in Django
What Is _Future_ in Python Used for and How/When to Use It, and How It Works
Simple Argparse Example Wanted: 1 Argument, 3 Results
How to Remove Packages Installed with Python's Easy_Install
How to Check the Versions of Python Modules
In Pytest, What Is the Use of Conftest.Py Files
Peak-Finding Algorithm for Python/Scipy
When I Catch an Exception, How to Get the Type, File, and Line Number
How to Find Out the Number of Cpus Using Python
Libxml Install Error Using Pip
Installing Pip Packages to $Home Folder