简体   繁体   English

Python:生成不在列表中的随机整数

[英]Python: Generate random integer that is not in a list

I am very new to Python (and coding in general). 我是Python的新手(一般编码)。 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. 我正在尝试创建一个创建列表副本的函数,其中字符串“rand”的任何实例都替换为随机整数。 The function will be called several times, with a new input_list each time. 该函数将被调用多次,每次都有一个新的input_list。 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. 我们可以假设没有重复的整数,但“rand”字符串可能会多次出现。 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. 这将保留一set剩余选项,只要将新值添加到输出列表,该选项就会减少。 Whenever a random number is needed, it will use choice to take a random element from that set . 每当需要随机数时,它将使用choice从该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). 直到你得到更大的数字环路初看起来似乎可行,让你有,直到找到一个有效的随机号码重试了很多(如randint(0, 100000)在99990个元素的列表)。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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