First, let's create a collection from A without repeated values:
ASemRepetidos = set(A)
For each element of this set, we will find the indexes of its occurrences in A. When you need indexes, the enumerate
function is your friend. With her help and a list comprehension , we set up this function:
def indicesDeElementoNaLista(elementoProcurado, lista):
return [i for (i, elemento) in enumerate(lista) if elemento == elementoProcurado]
So 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, let's go to our program:
The most appropriate data structure to generate variables "dynamically", as you are wanting with your nova_lista(x)
is mapping , or, in Python parlance, a dictionary in>. 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 sample, 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 modular and B is out of scope):
for chave in dicionarioResultante.keys():
print("Número: " + str(chave) + ". Valores correspondentes de B: " + str(dicionarioResultante[chave]))