如何在python中生成8个唯一数字的数组?

2024-09-29 23:24:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数,一个接一个地生成8个从1到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个数字多次,我不知道这是否与已经存在的问题有关,但它可以帮助解释发生了什么。你知道吗


Tags: thetoinforisvaluelinerandom
2条回答

对于你想要的方式:

import random #Allows the program to generate random numbers

correctSequence = [] #Defines array

def generateSequence(correctSequence): #Defines function, passes array as parameter
    while len(correctSequence) < 8:
        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(selection) if selection not in correctSequence else None
    return correctSequence

generateSequence(correctSequence) #The function is called
print(correctSequence) #The array is printed

但有更好的方法,例如:

import random #Allows the program to generate random numbers

def generateSequence():
    return random.sample([1,2,3,4,5,6,7,8], 8)
print(generateSequence())

或者将上面提到的return更改为return random.sample(range(1, 9), 8),以获得更简洁的效果。你知道吗

8 random numbers from 1 to 8 and adds them to an array, checking if they are unique each time before adding them

这里没有什么“随机”的。你所需要做的就是把数字1到8洗牌。你知道吗

import random

nums = list(range(1, 9))
random.shuffle(nums)
print(nums)
# [2, 6, 4, 3, 1, 7, 8, 5]

相关问题 更多 >

    热门问题