簡體   English   中英

在python中創建一個沒有重復的隨機數列表

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

所以我想做的是為游戲策划者創建一個包含 5 個數字的列表,我想消除所有重復項! 問題是代碼有時會創建一個包含 3 個數字或 4 個或有時 5 個數字的列表,它似乎是隨機的。

我還要提一下,我們不允許使用 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()

如果您正在尋找有效且更快的方法,請使用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]

或者,您可以將np.random.choicereplace=False一起使用:

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

嘗試使用帶有檢查 lis 長度的條件的 while 循環

while len(lis) < 5:

而不是你的 for 循環

函數random.sample做你想做的事:

import random

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

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

我不推薦這個答案中的解決方案 - 標准庫中的最佳選擇可能是random.sample ,並且可能有更有效的方法使用 numpy。 在其他答案中建議了這兩個選項。


此方法使用random.shuffle隨機播放數字列表,然后選擇前五個。 這避免了理論上無界循環的問題( while len(nums) < 5: ),但是當可供選擇的數字范圍(此處為 1 到 9)明顯大於所需的數字數量時(在這里,5)。

import random

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

您不想添加 5 次隨機的唯一整數; 您想添加隨機的唯一整數,直到您的列表包含 5 個元素。 這會做到:

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

所以你的問題:它不會兩次添加相同的數字。 但是由於您使用 a for i in range(5):它只會重復 5 次,無論它是否添加了唯一數字。

您需要測量列表的長度,因此它總是會在列表中添加 5 個隨機的、唯一的數字。

你的代碼大部分是正確的,但你需要做的就是替換: for i in range(5): with: while len(lis) < 5:

確保刪除i += 1 如果不這樣做會導致錯誤。

這是代碼:

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