Finding values in a python array and assigning specific values

0

I have the following vector:

posicao = [47, 62, 24, 18, 47, 62, 63, 78, 68, 87, 24, 18, 68, 87, 63, 78]

I need to look at this vector for values [24, 18].

After locating all, I need to assign a random value to these positions, but EQUAL.

I'm trying in various ways, but I can not.

Could anyone help me?

Thank you to those who can.

    
asked by anonymous 10.08.2017 / 03:49

1 answer

1

In this case the random value is generated at the beginning and only once, which will then be applied to all substitutions. These can be made based on a list of values to replace, and traversing the two, with a double for :

import random

posicao = [47, 62, 24, 18, 47, 62, 63, 78, 68, 87, 24, 18, 68, 87, 63, 78]
aleatorio = random.randrange(0,200)

for j in range(len(posicao)): #percorrer a lista original
    if posicao[j] in [24,18]: #ver se o elemento se encontra nos que se quer trocar
        posicao[j] = aleatorio #fazer a troca

Another solution is to use the index method of the array to find the element. And although it is simpler it throws an exception if the element does not exist, which in this case would be if the element that wants to put the random does not exist in the array posicao .

Controlling these exceptions already would look like this:

import random

posicao = [47, 62, 24, 18, 47, 62, 63, 78, 68, 87, 24, 18, 68, 87, 63, 78]
aleatorio = random.randrange(0,200)

for i in [24,18]: #valores a colocar o mesmo aleatório
    try:
        posicao[posicao.index(i)] = aleatorio
    except:
        pass

Edit

For index search and substitution you can do:

import random

posicao = [47, 62, 24, 18, 47, 62, 63, 78, 68, 87, 24, 18, 68, 87, 63, 78]
aleatorio = random.randrange(0,200)

for i in [2, 3, 10, 11]: #indices a substituir aqui no for
    posicao[i] = aleatorio
    
10.08.2017 / 04:30