Python 在一个范围内生成'n'个唯一的随机数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22842289/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:47:53  来源:igfitidea点击:

Generate 'n' unique random numbers within a range

pythonrandomunique

提问by Chris Headleand

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

我知道如何在 Python 中生成一个范围内的随机数。

random.randint(numLow, numHigh)

And I know I can put this in a loop to generate n amount of these numbers

我知道我可以把它放在一个循环中来生成 n 个这些数字

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?

但是,我需要确保该列表中的每个数字都是唯一的。除了大量的条件语句之外,是否有一种直接的方法可以生成 n 个唯一的随机数?

The important thing is that each number in the list is different to the others..

重要的是列表中的每个数字都与其他数字不同。

So

所以

[12, 5, 6, 1] = good

[12, 5, 6, 1] = 好

But

[12, 5, 5, 1] = bad, because the number 5 occurs twice.

[12, 5, 5, 1] = bad,因为数字 5 出现了两次。

采纳答案by Two-Bit Alchemist

If you just need sampling without replacement:

如果您只需要取样而不更换:

>>> import random
>>> random.sample(range(1, 100), 3)
[77, 52, 45]

random.sampletakes a population and a sample size kand returns krandom members of the population.

random.sample采用总体和样本大小,k并返回k总体中的随机成员。

If you have to control for the case where kis larger than len(population), you need to be prepared to catch a ValueError:

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

>>> try:
...   random.sample(range(1, 2), 3)
... except ValueError:
...   print('Sample size exceeded population size.')
... 
Sample size exceeded population size

回答by thefourtheye

Generate the range of data first and then shuffle it like this

先生成数据范围,然后像这样shuffle

import random
data = range(numLow, numHigh)
random.shuffle(data)
print data

By doing this way, you will get all the numbers in the particular range but in a random order.

通过这样做,您将获得特定范围内的所有数字,但顺序是随机的。

But you can use random.sampleto get the number of elements you need, from a range of numbers like this

但是您可以使用random.sample从这样的数字范围中获取所需元素的数量

print random.sample(range(numLow, numHigh), 3)

回答by mhlester

You could add to a setuntil you reach n:

您可以添加到 aset直到达到n

setOfNumbers = set()
while len(setOfNumbers) < n:
    setOfNumbers.add(random.randint(numLow, numHigh))

Be careful of having a smaller range than will fit in n. It will loop forever, unable to find new numbers to insert up to n

小心使用比适合的范围更小的范围n。它将永远循环,无法找到要插入的新数字n

回答by maxbublis

You could use the random.samplefunction from the standard libraryto select kelements from a population:

您可以使用标准库中random.sample函数从种群中选择k 个元素:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islicewith an infinite random generator:

如果可能的数字范围相当大,您可以使用itertools.islice无限随机生成器:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need ndistinct (unique) numbers.

问题更新后,现在很明显您需要n 个不同(唯一)的数字。

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
    items.add(x)