【发布时间】:2019-12-28 20:10:39
【问题描述】:
我正在尝试创建一个函数,该函数一个一个地生成从 1 到 8 的 8 个随机数并将它们添加到一个数组中,每次添加它们之前检查它们是否是唯一的。但是,它并没有按预期工作,虽然它创建了一个由 8 个元素组成的数组,但这些数字并不都是唯一的。我的代码:
import random #Allows the program to generate random numbers
correctSequence = [] #Defines array
def generateSequence(correctSequence): #Defines function, passes array as parameter
selection = random.randint(1,8) #Creates a random number and adds it to the array so there is a starting point for the for loop (Ln 10)
correctSequence.append(str(selection))
while len(correctSequence) < 8: #The while loop will continue to run until the array consists of 8 objects
selection = random.randint(1,8) #Generates a random number
for i in range(len(correctSequence)): #Loops through each value in the array
if correctSequence[i] == selection: #This line checks to see if the value already exists in the array
print("Duplicate") #This line is meant to print "Duplicate" when a duplicate value is generated
else:
correctSequence.append(str(selection)) #If the value doesnt already exist in the array, it will be added
print("Valid") #This line is meant to print "Valid" when a unique value is generated and added to the array
return correctSequence
#Main body of program
generateSequence(correctSequence) #The function is called
print(correctSequence) #The array is printed
我认为问题出现在第 10 行附近,因为程序似乎直接进入 else 语句,但我不明白为什么会发生这种情况。
此外,当我运行程序时,打印的数组似乎总是多次重复相同的 2 或 3 个数字,我不知道这是否与已经存在的问题有关,但它可以帮助解释什么是继续。
【问题讨论】:
-
random.sample([1,2,3,4,5,6,7,8], 8)怎么样? -
它无法工作,因为您将数字的 string 版本附加到列表中,然后检查列表中是否有整数。附加号码时为什么要在号码上调用
str()? -
或
random.sample(range(1, 9), 8)。另请注意,Python 没有数组。这些是列表。 -
@ggorlen 这些是列表,但 Python 确实有数组
-
@ggorlen docs.python.org/3/library/array.html
标签: python python-3.x list