Correlating vectors through indexes in Python

0

I have the following vectors:

posicao_1 = [4, 62, 24, 18, 47, 62, 63, 78, 68, 87, 24, 18, 6, 8, 12, 17]

posicao_2 = [43, 61, 21, 19, 46, 63, 68, 72, 66, 89, 29, 10, 8, 7, 6, 15]

I need to look at the vector POSITION_1 the value [24, 18].

posicao_1 = [4, 62, **24, 18**, 47, 62, 63, 78, 68, 87, **24, 18**, 6, 8, 12, 17]

We can see that they are found in the indexes [2, 3] and [10, 11] of the POSITION_1 vector.

After locating these values, I need to traverse the POSITION_2 vector and assign random and EQUAL values to the INDEXES [2, 3] and [10, 11] that I found in the POSITION_1 vector. For example:

You would have to assign random and EQUAL values:

posicao_2 = [43, 61, **21, 21**, 46, 63, 68, 72, 66, 89, **21, 21**, 8, 7, 6, 15]

Could someone please help me?

Sorry, if it was not very clear, I tried to explain as much as possible!

    
asked by anonymous 11.08.2017 / 00:50

1 answer

1

From the code of your last question, you just need to create an index list and save the elements where this code is putting the random ones. Then use it to replace in the second vector posicao_2

So:

import random
aleatorio = random.randrange(0,200)

posicao_1 = [4, 62, 24, 18, 47, 62, 63, 78, 68, 87, 24, 18, 6, 8, 12, 17]
posicao_2 = [43, 61, 21, 19, 46, 63, 68, 72, 66, 89, 29, 10, 8, 7, 6, 15]
indices = [] #lista criada aqui

for j in range(len(posicao_1)):
    if posicao_1[j] in [24,18]:
        posicao_1[j] = aleatorio
        indices.append(j) #indice adicionado aqui, quando coloca aleatorios em posicao_1

for i in indices: #atribuição em posicao_2 com base nos indices
    posicao_2[i] = aleatorio

Edit

For the exchange to be done just by searching for [24,18] as a sub-array, you need to slightly modify the logic that was being done.

...
#imports e posições para cima iguais 
pesq = [24,18]

#construir os indices verificando se a partir de cada posição o subarray existe no principal
indices = [x for x in range(len(posicao_1)) if posicao_1[x:x+len(pesq )] == pesq ]

#para cada indice substituir o subarray pela mesma quantidade de aleatorios
for i in indices:
    posicao_2[i: i+len(pesq)] = [aleatorio] * len(pesq)

To search multiple tuples, simply transform the search array into an array of tuples and create another for :

pesq = [[24,18], [62,63]]

for p in pesq:
    indices = [x for x in range(len(posicao_1)) if posicao_1[x:x+len(p)] == p ]

    for i in indices:
        posicao_2[i: i+len(p)] = [aleatorio] * len(p)
    
11.08.2017 / 02:48