Extract index for repeated elements in Python lists

Asked

Viewed 1,821 times

4

In case I have a list x that contains several values, and some repeated, and I want to have the index for each element, as I can do? I tried to do using the method .index() but it only returns the index of the first element.

>>> x = ['c','a','s','a']

>>> a.index('a')
1

But what I’m trying to do is to have the index of each letter, even though I have two numbers for the repeated letters and move on to a dictionary:

x_index = {"c":0,"a":(1,3),"s":2}
  • In the dictionary x_index, contents must be stored in tuples/integers or can be stored in arrays?

1 answer

5


You can use the enumerate to iterate over the list and get the index of the repeated elements:

>>> lista = ['c', 'a', 's', 'a']
>>> [i for i, item in enumerate(lista) if item == 'a']
[1, 3]
>>> 

To store repeated values and indexes in a dictionary, first check if the key already exists, if so, you get the repeated indexes and update the key, otherwise just enter the value:

dicionario = {}
lista = ['c', 'a', 's', 'a', 's']

for valor in lista:
    if valor in dicionario:
        dicionario[valor] = [i for i, item in enumerate(lista) if item == valor]
    else:
        dicionario[valor] = lista.index(valor)

print (dicionario)
# {'a': [1, 3], 'c': 0, 's': [2, 4]}

See DEMO

The dictionary order will not always be the same, if you need the order to be preserved, use a collections.OrderedDict:

from collections import OrderedDict

dicionario = OrderedDict()
# ...

print (dicionario)
# OrderedDict([('c', 0), ('a', [1, 3]), ('s', [2, 4])])    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.