简体   繁体   English

在python中创建一个没有重复的随机数列表

[英]Creating a list of random numbers without duplicates in python

so what I am trying to do is create a list of 5 numbers for the game mastermind, and I would like to eliminate all duplicates!所以我想做的是为游戏策划者创建一个包含 5 个数字的列表,我想消除所有重复项! The issue is that the code sometimes creates a list with 3 numbers, or 4, or sometimes 5, it seems to be random.问题是代码有时会创建一个包含 3 个数字或 4 个或有时 5 个数字的列表,它似乎是随机的。

I should also mention we are not allowed to be usin grandom.sample, or random.shuffle我还要提一下,我们不允许使用 grandom.sample 或 random.shuffle

import random

def generatePassword() :
    lis = []
    for i in range(5) :
        #This checks to see if there are duplicate numbers
        r = random.randint(1,9)
        if r not in lis :
            lis.append(r)
        i+=1
    return lis



def main() :
    print(generatePassword())
main()

Use numpy.random.permutation if you are looking for method that works and is faster:如果您正在寻找有效且更快的方法,请使用numpy.random.permutation

import numpy as np
your_list = list(np.random.permutation(np.arange(0,10))[:5])

>>> your_list
[6, 9, 0, 1, 4]

Alternatively, you can use np.random.choice with replace=False :或者,您可以将np.random.choicereplace=False一起使用:

your_list = list(np.random.choice(np.arange(0,10), 5, replace=False)

Try using a while loop with a condition that checks for the length of lis尝试使用带有检查 lis 长度的条件的 while 循环

while len(lis) < 5:

instead of your for loop而不是你的 for 循环

The function random.sample does what you want:函数random.sample做你想做的事:

import random

def generatePassword():
    numbers = range(0, 9)
    return random.sample(numbers, 5)

def main() :
    print(generatePassword())
main()

I do not recommend the solution in this answer - the best option in the standard library is probably random.sample , and there may be more efficient methods using numpy.我不推荐这个答案中的解决方案 - 标准库中的最佳选择可能是random.sample ,并且可能有更有效的方法使用 numpy。 Both of these options are suggested in other answers.在其他答案中建议了这两个选项。


This method uses random.shuffle to shuffle a list of digits, then selects the first five.此方法使用random.shuffle随机播放数字列表,然后选择前五个。 This avoids the issue of a theoretically unbounded loop ( while len(nums) < 5: ), but does not scale well when the range of numbers to choose from (here, 1 to 9) is significantly larger than how many numbers are needed (here, 5).这避免了理论上无界循环的问题( while len(nums) < 5: ),但是当可供选择的数字范围(此处为 1 到 9)明显大于所需的数字数量时(在这里,5)。

import random

population = list(range(1, 10))
random.shuffle(population)
print(population[:5])

You don't want to add random, unique integers 5 times;您不想添加 5 次随机的唯一整数; you want to add random, unique integers until your list contains 5 elements.您想添加随机的唯一整数,直到您的列表包含 5 个元素。 This'll do it:这会做到:

import random

def generatePassword() :
    lis = []
    while len(lis) < 5:
        #This checks to see if there are duplicate numbers
        r = random.randint(1,9)
        if r not in lis :
            lis.append(r)
    return lis

So your problem: It won't add the same number twice.所以你的问题:它不会两次添加相同的数字。 But since you use a for i in range(5): it will only repeat 5 times, regardless of if it added a unique number or not.但是由于您使用 a for i in range(5):它只会重复 5 次,无论它是否添加了唯一数字。

You need to measure the length of the list, so it will always add 5 random, unique numbers to the list.您需要测量列表的长度,因此它总是会在列表中添加 5 个随机的、唯一的数字。

You have the code mostly right, but all you need to do is replace: for i in range(5): with: while len(lis) < 5:你的代码大部分是正确的,但你需要做的就是替换: for i in range(5): with: while len(lis) < 5:

Make sure to delete the i += 1 though.确保删除i += 1 It will cause an error if you don't.如果不这样做会导致错误。

Here's the code:这是代码:

import random

def generatePassword() :
    lis = []
    while len(lis) < 5:
        #This checks to see if there are duplicate numbers
        r = random.randint(1,9)
        if r not in lis :
            lis.append(r)
    return lis



def main() :
    print(generatePassword())
main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM