简体   繁体   中英

How to get the indexes of the same values in a list?

Say I have a list like this:

l = [1, 2, 3, 4, 5, 3]

how do I get the indexes of those 3s that have been repeated?

First you need to figure out which elements are repeated and where. I do it by indexing it in a dictionary.

Then you need to extract all repeated values.

from collections import defaultdict

l = [1, 2, 3, 4, 5, 3]
_indices = defaultdict(list)

for index, item in enumerate(l):
    _indices[item].append(index)

for key, value in _indices.items():
    if len(value) > 1:
        # Do something when them
        print(key, value)

Output:

3 [2, 5]

Another would be to filter them out like so:

duplicates_dict = {key: indices for key, indices in _indices.items() if len(indices) > 1}

you could use a dictionary comprehension to get all the repeated numbers and their indexes in one go:

L = [1, 2, 3, 4, 5, 3, 8, 9, 9, 8, 9]

R = { n:rep[n] for rep in [{}] for i,n in enumerate(L) 
      if rep.setdefault(n,[]).append(i) or len(rep[n])==2 }

print(R)

{3: [2, 5], 
 9: [7, 8, 10], 
 8: [6, 9]}

The equivalent using a for loop would be:

R = dict()
for i,n in enumerate(L):
    R.setdefault(n,[]).append(i)
R = {n:rep for n,rep in R.items() if len(rep)>1}

Counter from collections could be used to avoid the unnecessary creation of single item lists:

from collections import Counter
counts = Counter(L)
R = dict()
for i,n in enumerate(L):
    if counts[n]>1:
       R.setdefault(n,[]).append(i)

find deplicates and loop through the list to find the corresponding index locations. Not the most efficient, but works

input_list = [1,4,5,7,1,2,4]
duplicates = input_list.copy()

for x in set(duplicates):
    duplicates.remove(x)

duplicates = list(set(duplicates))
dict_duplicates = {}
for d in duplicates:
    l_ind = []
    dict_duplicates[d] = l_ind    
    for i in range(len(input_list)):
        if d == input_list[i]:
            l_ind.append(i)
dict_duplicates            

This should do it

list = [1,2,3,4,5,3]
deletes = 0;
for element in list:
   if element == 3:
       print(list.index(element) + deletes)
       deletes = +1;
       list.remove(3)


We get the index of the element, remove one so it can find the next one and increment by 1 the next index so it matches the original list index. Outputs:

2
5
l = [1,2,3,4,5,3]

for i in range(len(l)):
    for j in range(i + 1 , len(l)):
        if l[i] == l[j]:
            z = f"{l[i]}  have been repeated in {i} , {j}"
            print(z)
            

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM