简体   繁体   中英

How to generate a unique single random number each time in a loop in Python?

I know there are some similar questions,but all of them just return a list,I just need a number,each time random generate a unique single number:

Now I'm using Python to build a loop:

for _ in range(9):
        random_number=random.randint(1,11)
        print(random_number)

My question is how to make sure each time the random_number is unique,not repeating in all 9 times. I don't need a list,just the random_number

You can use random.sample over the target range of numbers to pick a desired number of unique numbers from them:

import random
for random_number in random.sample(range(1, 12), 9):
    print(random_number)

If you want each number to be unique from all the others, you don't want a truly random number each time (it's in fact very improbable for random numbers within a small set to be unique). I'd do it like this:

numbers = list(range(1, 12))
random.shuffle(numbers)
for random_number in numbers[:9]:
    print(random_number)

Essentially it's like taking a deck of cards, shuffling it, and then dealing the top nine cards. You'll get nine "random" cards but they will never repeat since they're coming from the same deck and you aren't reshuffling in between deals (consequently they aren't truly random, which is why card-counting is a thing).

random.sample is definitely the way to go, but another idea is to initialize all numbers in a list and then randomly pop one at a time:

import random

numbers = list(range(1, 12))
for _ in range(9):
    random_index = random.randint(0, len(numbers)-1)
    selected_rn = numbers.pop(random_index)

This has a nice interpretation: a predefined sequence of numbers that you point to a number of times and grab one number at random.

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