我现在并不擅长编码,我正在努力改进和学习。自动取款机,我试图写一个代码,随机选择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)发布于 2017-05-26 17:58:34
all = a, b, c, x, y, z这样的东西创造了一个元组的价值。因此,在行执行时,元组内部有固定的值,不能更改。当您更新最初用于构造它的变量之一时,它尤其不会改变。因此,您不能使用all作为最终结果,也不能使用outX元组检查任何副本,因为它们是固定的,不会更新。
为了使代码工作,您必须在while循环的每一次迭代中重新创建所有这些元组。但是通常,您很快就会注意到,拥有这些显式变量并不是一个好主意。
如果您想继续使用randint,那么您可以一次生成一个数字,并且每当您遇到一个已经拥有的数字时,就可以生成“reroll”:
numbers = []
while len(numbers) < 6:
num = random.randint(1, 100)
if num not in numbers:
numbers.append(num)这里我使用一个list,它是一个可变的数据结构,用于收集多个值(与不可变的元组相比)。
您还可以在这里使用random.sample,它提供了一种从一系列数字中获取任意数量的唯一值的更简单的方法:
numbers = random.sample(range(1, 100), 6)发布于 2017-05-26 17:49:39
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)如果您的列表比6大得多,您可以考虑使用set而不是list。
更新:--实际上,random.sample()非常聪明,使用python3时,代码如下:
all = random.sample(range(1,10000000001), 6)工作得很好,而这个:
all = random.sample(list(range(1,10000000001)), 6)吃了我所有的记忆。
如果您使用python2,您可以使用xrange而不是range来获得相同的效果。
发布于 2017-05-26 17:51:10
而不是创建6个不同的变量,您可以创建一个使用random.sample生成6个唯一数字的列表。
import random
nums = random.sample(range(1,100), 6)
print (nums)
Output:
[2,34,5,61,99,3]https://stackoverflow.com/questions/44207412
复制相似问题