简体   繁体   中英

Python: Generate random integer that is not in a list

I am very new to Python (and coding in general). I am trying to create a function which creates a duplicate of a list, with any instances of the string "rand" replaced with a random integer. The function will be called several times, with a new input_list each time. These new items should be appended to the existing output list. We can assume there will be no repeated integers, but the "rand" string may appear many times. This is my current code. It does very close to what I want except that when the random number is already on the list, it just moves on to the next item rather than trying to create a new random number. Can anyone help me out with this? Thank you in advance.

import random
input_list = [1, 3, "rand", 2]
def number_adder(input_list):
  output_list = []

  for item in my_list:
    if item == "rand":
      new_variable = int(random.randint(0, 4))
      if new_variable in output_list:
        continue
    else:
      new_variable = item

  output_list.append(new_variable)
return output_list
import random

input_list = [1, 3, "rand", 2]
output_list = []

options = set(range(5))
for item in input_list:
  if item == "rand":
    new_variable = random.choice(list(options))
  else:
    new_variable = item
  output_list.append(new_variable)
  options -= set([ new_variable ])

You could do it like this. But this would mean that in if no random number can be found which is possible anymore, then this will throw an exception.

This will keep a set of remaining options which is reduced whenever a new value is added to the output list. Whenever a random number is needed, it will use choice to take a random element from that set . This way you do not have to use a loop to call the random functions repeatedly until you find a valid random number.

A loop might seem feasible at first until you get to larger numbers so that you have to retry a lot until you find a valid random number (eg randint(0, 100000) in a list of 99990 elements). This would unnecessarily slow your code down.

Actually, I'd rephrase the code a little, using a generator:

def fill_randoms(list_with_randoms, options):
  for item in list_with_randoms:
    value = random.choice(list(options)) if item == 'rand' else item
    yield value
    options -= set([ value ])

And I'd call it like this:

list(fill_randoms([1, 3, "rand", 2], set(range(5))))

But if you are not familiar with generators, stick to the other code.

Loop while the number is in the output list:

if item == "rand": 
    new_variable = int(random.randint(0, 4))
    while new_variable in output_list:
        new_variable = int(random.randint(0, 4))

I fixed the error pointed out in the comments. Here are two functions that satisfy your ask:

import random
input_list = [1, 3, "rand", 2]

def rand_replacer(my_list):
    output_list = []
    for item in my_list:
        if item == "rand":
            while True:
                new_variable = random.randint(0, 4)
                if new_variable not in my_list:
                    output_list.append(new_variable)
                    break
        else:
            output_list.append(item)
    return output_list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM