initial index of a list after using set

0

I used this code initially to aggregate the values of B that had equal value in A into dictionaries:

A = [12,   15,  10,  15,  12,  10,  10,  10,  15,  12,  12,  15,  15,  15]
B = [0.2, 0.3, 1.1, 0.2, 0.2, 0.7, 0.4, 0.6, 0.1, 0.3, 0.7, 0.4, 0.5, 0.5]

ASemRepetidos = set(A)

def indicesDeElementoNaLista(elementoProcurado, lista):
    return [i for (i, elemento) in enumerate(lista) if elemento == elementoProcurado]

def elementosNasPosicoes(lista, posicoes):
    return [lista[i] for i in posicoes]

dicionarioResultante = {} 

for elemento in ASemRepetidos:
    posicoes = indicesDeElementoNaLista(elemento, A)
    elementosCorrespondentes = elementosNasPosicoes(B, posicoes)
    dicionarioResultante[elemento] = elementosCorrespondentes

print(dicionarioResultante)

And the result was:

{10: [1.1, 0.7, 0.4, 0.6], 12: [0.2, 0.2, 0.3, 0.7], 15: [0.3, 0.2, 0.1, 0.4, 0.5, 0.5]}

But by doing this, set(A) changes the order of the elements and I needed the original order of A to find in a 3rd list the values of this that have the same index as A and not that ASemRepetidos , because this list is much smaller than A , in addition to being "disordered" due to the application of the set. How can I know the index of repeats the first time they appear in the original list A and not their index in the list of not repeated ( ASemRepetidos )? That is, I wanted a general function that would return me that the index of 12 is 0, that of 15 is 1 and that of 10 is 2? I tried to do:

indice=[] 
for k in range(0,len(A)):
    for chave in ASemRepetidos: 
        indice.append(A.index(chave)) 
print indice

But it did not work ...
Can anyone help?

    
asked by anonymous 07.04.2016 / 14:16

1 answer

0

If I understood correctly what you are trying to do the following solution should solve the problem:

indice=[]
feitos = [] # vou guardar aqui todas as chaves que já ocorreram no loop.
indic = {} # Se quiseres ter uma ligação directa entre chave e indice...
for k in A:
    if k in ASemRepetidos and k not in feitos: 
        indice.append(A.index(k))
        feitos.append(k)
        indic[k]=A.index(k)
print(indice)
print(indic)

Notice that I put a dictionary that is not necessary to solve the problem, but it helps to confirm the values requested by you. The dictionary has as key the values of A and as value the indices of the occurrences. The result is:

[0, 1, 2]
{10: 2, 12: 0, 15: 1}
    
07.04.2016 / 19:18