Extract index for repeated elements in lists in Python

4

If I have a x list that contains multiple values, and a few repeats, and I want to have the index for each element, how can I do it? I tried doing it using the .index() method but it only returns the index of the first element.

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

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

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

x_index = {"c":0,"a":(1,3),"s":2}
    
asked by anonymous 17.09.2016 / 17:26

1 answer

5

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

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

To save the repeated values and indexes in a dictionary , first check that 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 preserved, use collections.OrderedDict :

from collections import OrderedDict

dicionario = OrderedDict()
# ...

print (dicionario)
# OrderedDict([('c', 0), ('a', [1, 3]), ('s', [2, 4])])    
    
17.09.2016 / 18:58