Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomly replace a string in a list

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 = ['-','*','-','-','-','*','*']
like image 534
JJHH Avatar asked Feb 20 '26 05:02

JJHH


2 Answers

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.

like image 132
Edgar Andrés Margffoy Tuay Avatar answered Feb 22 '26 19:02

Edgar Andrés Margffoy Tuay


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)
like image 43
Damian Avatar answered Feb 22 '26 19:02

Damian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!