First, let’s create a collection from A without repeated values:
ASemRepetidos = set(A)
For each element of this set, we will find the index of its occurrences in A. When you need indexes, the function enumerate
is your friend. With her help and a comprehensilist on, we set up this function:
def indicesDeElementoNaLista(elementoProcurado, lista):
return [i for (i, elemento) in enumerate(lista) if elemento == elementoProcurado]
With this, we need to get the values of B corresponding to these positions. Let’s do another function for this:
def elementosNasPosicoes(lista, posicoes):
return [lista[i] for i in posicoes]
With these functions, we go to our program:
The most suitable data structure to generate variables "dynamically" as you want with your nova_lista(x)
is the mapping, or, in Python’s language, a dictionary. Let’s create a dictionary whose keys are the unique elements of A and values are the corresponding values of B. With the above functions, it’s simple:
dicionarioResultante = {} # coloque um nome mais adequado ao seu contexto
for elemento in ASemRepetidos:
posicoes = indicesDeElementoNaLista(elemento, A)
elementosCorrespondentes = elementosNasPosicoes(B, posicoes)
dicionarioResultante[elemento] = elementosCorrespondentes
print(dicionarioResultante)
Applying this to your input example, we have the output:
{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]}
An example of using the result:
for chave in ASemRepetidos:
print("Número: " + str(chave) + ". Valores correspondentes de B: " + str(dicionarioResultante[chave]))
Or, using only dictionary methods (more interesting if your code is modularized and B is out of scope):
for chave in dicionarioResultante.keys():
print("Número: " + str(chave) + ". Valores correspondentes de B: " + str(dicionarioResultante[chave]))
It has no value of B that is equal to that of A. I believe there are functions to make an intersection, difference, union of lists. I could explain better and if possible make an example in ideone?
– rray
What I intend is, to find the indices of A whose elements are equal (whenever they are 12 or whenever they are 15, or 10) and in a new list put the values of B of these repeated indices. Thus for the value 12 of A, it would have a list: nova_lista_12=[0.2, 0.2, 0.3, 0.7] with the B values of the indices where A is 12...
– Sofia Raimundo