如何生成唯一的随机数(不重复)? [英] How to generate unique random numbers (that don't repeat)?
问题描述
我正在尝试编写一个随机选择数字并将其添加到列表random_numbers
的代码,但是如果已经生成一个随机数字,则代码会检测到该数字并将其替换为另一个数字,直到每个数字都不同为止
I'm trying to write a code that randomly chooses numbers and adds them to the list random_numbers
, but if a random number was already generated, the code detects that and replaces the number with another, until every number is different.
import random
random_numbers = []
for x in range(11):
这部分生成一个随机整数并将其附加到列表random_numbers
:
This part generates a random integer and appends it to the list random_numbers
:
random_numbers.append('[q' + str(random.randint(1, 11)) + ']')
这部分应该遍历列表,检查是否已经生成了生成的随机数,并将其替换:
This part is supposed to iterate over the list and check if the random number generated was already generated, and replace it:
for item in range(len(random_numbers)):
if random_numbers[x] == random_numbers[item]:
random_numbers[x] = '[q' + str(random.randint(1, num_of_qs_in_file)) + ']'
print(random_numbers)
输出有所不同,但几乎总是列表具有相同的整数不止一次.有人可以帮忙吗?
The output varies, but almost always the list has the same integer more than once. Can anybody help?
推荐答案
在适度范围内进行非重复随机"(psudeorandom)整数的一种直接方法是使用range(1, n)
,然后使用pop()
或切片从列表中获取所需的数字.
One straightforward way to do non-repeating 'random' (psudeorandom) whole numbers in a modest range is to create a list using range(1, n)
, then random.shuffle()
the list, and then take as many numbers as you want from the list using pop()
or a slice.
import random
max = 11
l = list(range(1, max)) # the cast to list is optional in Python 2
random.shuffle(l)
现在,每次您想要一个随机数时,只需l.pop()
.
Now every time you want a random number, just l.pop()
.
另一种方法是使用random.sample()
-请参见 https://docs.python. org/3/library/random.html
Another is to use random.sample()
-- see https://docs.python.org/3/library/random.html
这篇关于如何生成唯一的随机数(不重复)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!