Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 制造6个不同的随机数_Python_Random_Numbers_Non Repetitive - Fatal编程技术网

Python 制造6个不同的随机数

Python 制造6个不同的随机数,python,random,numbers,non-repetitive,Python,Random,Numbers,Non Repetitive,我现在不太擅长编码,我正在努力改进和学习。我试图写一个随机选取6个不重复的数字的代码,但我失败了。我该怎么办 import random a = random.randint(1, 100) b = random.randint(1, 100) c = random.randint(1, 100) x = random.randint(1, 100) y = random.randint(1, 100) z = random.randint(1, 100) outa = b, c, x, y

我现在不太擅长编码,我正在努力改进和学习。我试图写一个随机选取6个不重复的数字的代码,但我失败了。我该怎么办

import random

a = random.randint(1, 100)
b = random.randint(1, 100)
c = random.randint(1, 100)
x = random.randint(1, 100)
y = random.randint(1, 100)
z = random.randint(1, 100)

outa = b, c, x, y, z
outb = a, c, x, y, z
outc = a, b, x, y, z
outx = a, b, c, y, z
outy = a, b, c, x, z
outz = a, b, c, x, y

all = a, b, c, x, y, z

while a in outa or b in outb or c in outc or x in outx or y in outy or z in outz:
    if a in outa:
        a = random.randint(1,100)
    elif b in outb:
        b = random.randint(1,100)
    elif c in outc:
        c = random.randint(1,100)
    elif x in outx:
        x = random.randint(1,100)
    elif y in outy:
        y = random.randint(1,100)
    elif z in outz:
        z = random.randint(1,100)

print(all)
像这样:

random.sample(range(1,100), 6)

random
中有一个函数,它的作用就是:

all = random.sample(range(1,101), 6)
如果可能值的列表太大而无法构建,则您的算法很好,但使用列表会更好:

all = []
while len(all) < 6:
    x = random.randint(1, 10000000)
    if not x in all:
        all.append(x)
很好用,而这个:

all = random.sample(list(range(1,10000000001)), 6)
吞噬了我所有的记忆


如果您使用python2,您可以使用
xrange
而不是
range
来获得相同的效果。

而不是创建6个不同的变量,您可以使用
random创建一个生成6个唯一数字的列表。示例

import random

nums = random.sample(range(1,100), 6)
print (nums)

Output:
[2,34,5,61,99,3]
这类事情会创建一个值元组。因此,在执行该行时,该元组内部有固定值,不能更改。当您更新最初用于构造它的一个变量时,它尤其不会更改。因此,您不能使用
all
获得最终结果,也不能使用
outX
元组检查任何重复项,因为它们是固定的,不会更新

为了让代码正常工作,您必须在while循环的每次迭代中重新创建所有这些元组。但一般来说,您会很快注意到,拥有这些显式变量不是一个好主意

如果您想继续使用
randint
,那么您可以一次生成一个数字,并在遇到已有数字时“重新滚动”:

numbers = []
while len(numbers) < 6:
    num = random.randint(1, 100)
    if num not in numbers:
        numbers.append(num)

你知道列表吗?“随机选取6个不重复的数字”:
random.sample(范围(1100),6)
这个问题中使用
sample
的所有建议(我的建议除外)都缺少范围内的100
range
不包含结束值,但
randint
包含结束值。在采样之前,任何将
range()
转换为
set
的理由似乎都会大大降低相同结果的速度。我认为你是对的,不需要设置。我来编辑。
all = a, b, c, x, y, z
numbers = []
while len(numbers) < 6:
    num = random.randint(1, 100)
    if num not in numbers:
        numbers.append(num)
numbers = random.sample(range(1, 100), 6)