如何生成唯一的随机数(不重复)?

编程入门 行业动态 更新时间:2024-10-13 08:21:37
本文介绍了如何生成唯一的随机数(不重复)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试编写一个随机选择数字并将其添加到列表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()-请参见 docs.python. org/3/library/random.html

Another is to use random.sample() -- see docs.python/3/library/random.html

更多推荐

如何生成唯一的随机数(不重复)?

本文发布于:2023-11-30 07:09:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649123.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!