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