问题描述
我知道如何在 Python 中生成一个范围内的随机数.
random.randint(numLow, numHigh)
而且我知道我可以把它放在一个循环中来生成 n 个这些数字
for x in range (0, n):listOfNumbers.append(random.randint(numLow, numHigh))
但是,我需要确保该列表中的每个数字都是唯一的.除了大量的条件语句,是否有一种直接的方法可以生成 n 个唯一的随机数?
重要的是列表中的每个数字都与其他数字不同..
所以
[12, 5, 6, 1] = 好
但是
[12, 5, 5, 1] = bad,因为数字 5 出现了两次.
如果您只需要采样而不更换:
<预><代码>>>>随机导入>>>random.sample(范围(1, 100), 3)[77, 52, 45]random.sample 需要一个总体和一个样本大小k
并返回 k
个随机的总体成员.
如果你必须控制k
大于len(population)
的情况,你需要准备捕捉ValueError
>:
I know how to generate a random number within a range in Python.
random.randint(numLow, numHigh)
And I know I can put this in a loop to generate n amount of these numbers
for x in range (0, n):
listOfNumbers.append(random.randint(numLow, numHigh))
However, I need to make sure each number in that list is unique. Other than a load of conditional statements, is there a straightforward way of generating n number of unique random numbers?
The important thing is that each number in the list is different to the others..
So
[12, 5, 6, 1] = good
But
[12, 5, 5, 1] = bad, because the number 5 occurs twice.
If you just need sampling without replacement:
>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]
random.sample takes a population and a sample size k
and returns k
random members of the population.
If you have to control for the case where k
is larger than len(population)
, you need to be prepared to catch a ValueError
:
>>> try:
... random.sample(range(1, 2), 3)
... except ValueError:
... print('Sample size exceeded population size.')
...
Sample size exceeded population size
这篇关于在一个范围内生成'n'个唯一的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2