简体   繁体   English

Python中如何在循环中每次生成唯一的单个随机数?

[英]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:现在我正在使用 Python 来构建一个循环:

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.我的问题是如何确保每次random_number都是唯一的,而不是在所有 9 次中重复。 I don't need a list,just the random_number我不需要列表,只需要 random_number

You can use random.sample over the target range of numbers to pick a desired number of unique numbers from them:您可以在目标数字范围内使用random.sample从中选择所需数量的唯一数字:

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: random.sample绝对是通往 go 的方法,但另一个想法是初始化列表中的所有数字,然后一次随机弹出一个:

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.这有一个很好的解释:一个预定义的数字序列,您指向它多次并随机获取一个数字。

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

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