3

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 = ['-','*','-','-','-','*','*']
JJHH
  • 67
  • 1
  • 9

7 Answers7

3

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.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 2
    Separate calls to randint can generate the same number. It might be better to use `random.sample`. – ayhan Apr 30 '16 at 18:24
2
import random as r

L = ['-','-','-','-','-','-','-']

def replaceit(L,char):
    L[r.randint(0,len(L))] = char
    return L

newL = replaceit(L,'*')
print newL

Simply call replaceit with newL to replace another random character.

Zack Tarr
  • 119
  • 1
  • 1
  • 11
2

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)
Damian
  • 548
  • 6
  • 14
1

use random.choice

import random

L = ['-','-','-','-','-','-','-']

while L.count('*') < 3:
    pos = random.choice(range(len(L)))
    L[pos] = '*'

print(L)
danidee
  • 9,298
  • 2
  • 35
  • 55
0

suppose u want to replace it with 'a' :

try the following:

from random import *

L = ['-','-','-','-','-','-','-']
r = randint(0,len(L))
L[r] = 'a'

print L
Mayur Buragohain
  • 1,566
  • 1
  • 22
  • 42
0

i have a Java background, a newbie to python. I will suggest to generate a random number from first to last index of that list, and insert the new string to the newly generated index.

Refer to this question to insert a value at a specific position in a list.

Community
  • 1
  • 1
Junaid
  • 9
  • 3
0

This non-repeat solution relies on random.shuffle():

>>> import random
>>> L = ['-','-','-','-','-','-','-']
>>> n = 3    # number of strings to replace
>>> indices = range(len(L))
>>> random.shuffle(indices)
>>> for i in indices[:n]:
...     L[i] = '*'
... 
>>> L
['-', '*', '*', '-', '*', '-', '-']
Tonechas
  • 13,398
  • 16
  • 46
  • 80