生成范围内的'n'个唯一随机数 [英] Generate 'n' unique random numbers within a range

查看:193
本文介绍了生成范围内的'n'个唯一随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何在Python中生成一个随机数.

I know how to generate a random number within a range in Python.

random.randint(numLow, numHigh)

我知道我可以将其放在循环中以生成n个数量的这些数字

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))

但是,我需要确保列表中的每个数字都是唯一的.除了加载条件语句外,还有一种直接的方法可以生成n个唯一的随机数吗?

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..

所以

[12,5,6,1] =好

[12, 5, 6, 1] = good

但是

[12,5,5,1] =不好,因为数字5出现两次.

[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 需要一个总体和一个样本量k并返回总体中的k个随机成员.

random.sample takes a population and a sample size k and returns k random members of the population.

如果必须控制k大于len(population)的情况,则需要准备捕获ValueError:

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'个唯一随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆