If I have something like this:
L = ['-','-','-','-','-','-','-']
And let's say that I want to replace certain number of those strings. How do I randomly select a position within the list to replace it for something else? For example:
L = ['-','*','-','-','-','*','*']
Actually, you can use the module random and its function randint, as it follows:
import random
num_replacements = 3
L = ['-','-','-','-','-','-','-']
idx = random.sample(range(len(L)), num_replacements)
for i in idx:
L[i] = '*'
For more information, you can check the random module documentation at: https://docs.python.org/3/library/random.html
EDIT: Now sampling random number using random.sample, rather than using random.randint, which may generate the same number during different iterations.
Use random.randrange
import random
some_list=["-","-","-","-","-","-","-"]
n=2
for i in range(n):
some_list[random.randrange(0,len(some_list))]="*"
Non-repeat solution:
import random
some_list=["-","-","-","-","-","-","-"]
n=8
if n>len(some_list):
some_list=["*" for i in some_list]
else:
for i in range(n):
position=random.randrange(0,len(some_list))
while some_list[position]=="*":
position=random.randrange(0,len(some_list))
some_list[position]="*"
print(some_list)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With