Generate 'n' unique random numbers within

2019-01-03 02:08发布

This question already has an answer here:

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?

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

4条回答
小情绪 Triste *
2楼-- · 2019-01-03 02:27

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

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:

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.

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)
查看更多
Root(大扎)
3楼-- · 2019-01-03 02:32

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
查看更多
何必那么认真
4楼-- · 2019-01-03 02:35

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)
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-03 02:45

You could add to a set until you reach 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

查看更多
登录 后发表回答