簡體   English   中英

如何限制生成特定隨機數的次數python

[英]How to limit the number of times a specific random number is generated python

我目前正在使用python中的記憶游戲作為一個類項目。 我試圖生成0到3之間的隨機數,這對應於某張卡。 問題是,我需要每張卡只出現兩次。 不多也不少。

這是我目前的代碼:

import random
cards = ["___TI___", "___GK___", "___QW___", "___KJ___"]
boardTemp1 = ['1', '2',
              '3', '4',
              '5', '6',
              '7', '8']

def shuffle():

    cardChoose = random.randint(0, 3)
    boardChoose = random.randint(0, 7)
    randCard = 9
    randCard = cards[cardChoose]
    boardTemp1[boardChoose] = cards[cardChoose]
    return randCard

boardTemp1[0] = shuffle()
boardTemp1[1] = shuffle()
boardTemp1[2] = shuffle()
boardTemp1[3] = shuffle()
boardTemp1[4] = shuffle()
boardTemp1[5] = shuffle()
boardTemp1[6] = shuffle()
boardTemp1[7] = shuffle()


print(boardTemp1)

謝謝你的幫助

當你有一組特定的項目時,進行獨立的隨機選擇並不是一個好方法。 試試這個:

import random
cards = ["___TI___", "___GK___", "___QW___", "___KJ___"]
boardTemp1 = cards * 2
random.shuffle(boardTemp1)
print(boardTemp1)

我會列出每張卡兩次並隨機列出清單而不是電路板,然后在將它們放在電路板上時從列表中刪除每張卡:

import random

cards = [1, 1, 2, 2, 3, 3, 4, 4]
random.shuffle(cards)

while cards:
    card = cards.pop()
    # place each card on the board sequentially

您可以將這些數字存儲在生成的兩個列表中嗎? 生成數字時:檢查列表:

-if number不在第一個列表中,添加它

-if number在第一個列表中,檢查第二個

- 如果數字不在第二個,添加它

-if number在第二個列表中,然后它已生成兩次,並從那里做你想要的,假設是生成另一個隨機數。

例如:

list1=[]
list2=[]
n=newly generated random number
if n not in list1:
    list1.append(n)
elif
  if n not in list2:
    list2.append(n)
else:
  #regenerate random number

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM