在一个范围内生成'n'唯一随机数[重复]

时间:2023-02-08 22:51:30

This question already has an answer here:

这个问题已经有了答案:

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个数的唯一随机数?

EDIT: 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] =坏,因为数字5发生了两次。

4 个解决方案

#1


189  

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.

随机的。样本取总体和样本大小k,返回总体中的k个随机成员。

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

如果你必须控制k大于len(总体)的情况,你需要准备捕捉ValueError:

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

#2


14  

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

首先生成数据的范围,然后像这样打乱它

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.sample to get the number of elements you need, from a range of numbers like this

但是你可以随意使用。从这样的数字范围中获取所需元素的数量

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

#3


12  

You could add to a set until you reach n:

你可以添加到一个集合,直到你到达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

#4


3  

You could use random.sample function from standard library to select k elements from population:

您可以使用随机的。来自标准库的样本函数从人群中选择k个元素:

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

In case of rather large range of possible numbers you could use itertools.islice with infinite random generator:

如果可能的数字范围很大,可以使用迭代工具。具有无限随机发生器的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

UPDATE

更新

So, after question update it is now clear, that you need n distinct (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)

#1


189  

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.

随机的。样本取总体和样本大小k,返回总体中的k个随机成员。

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

如果你必须控制k大于len(总体)的情况,你需要准备捕捉ValueError:

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

#2


14  

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

首先生成数据的范围,然后像这样打乱它

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.sample to get the number of elements you need, from a range of numbers like this

但是你可以随意使用。从这样的数字范围中获取所需元素的数量

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

#3


12  

You could add to a set until you reach n:

你可以添加到一个集合,直到你到达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

#4


3  

You could use random.sample function from standard library to select k elements from population:

您可以使用随机的。来自标准库的样本函数从人群中选择k个元素:

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

In case of rather large range of possible numbers you could use itertools.islice with infinite random generator:

如果可能的数字范围很大,可以使用迭代工具。具有无限随机发生器的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

UPDATE

更新

So, after question update it is now clear, that you need n distinct (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)