简体   繁体   中英

Create random number excluding numbers in a list

So let's say I have a list of numbers (not a specific range, which could change), and want to generate a random number which excludes the numbers in the list.

List of excluded numbers comes from a sql query.

and the only limit for the random number is the number of digits, which can come from:

random_number = ''.join(random.choice(chars) for _ in range(size))

so I want to generate the random number (with size limit) excluding a list of numbers.

while random_number in exclude_list:
    random_number = ''.join(random.choice(string.digits) for _ in range(size))

Is there a pythonic way (other than using while loop) to do that?

example: generate a 2digit random number which does not exist in a list of numbers like exclude_list=[22,34,56,78]

You may call the random.choice using set to exclude the items in list you do not want to be the part of random selection:

>>> import random

>>> my_list = [1, 2, 3, 4, 5, 6, 7]
>>> exclude_list = [3, 6, 7]

# list containing elements from `my_list` excluding those of `exclude_list`
>>> valid_list = list(set(my_list) - set(exclude_list))

>>> random.choice(valid_list)
5  # valid random number

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