[英]How do I select a random element from a 2d list
我正在嘗試在 python 的 2D 列表中選擇一個隨機元素。 我正在創建一個二十一點游戲。
我知道這段代碼有多長和未優化,但我是編程新手,我想犯錯誤來學習。
這是我設置的初始代碼。 我創造了套裝(黑桃、梅花、紅心、鑽石)。 我將它附加到名為 list_of_cards 的列表中,該列表被初始化為一個空數組。
然后我有另一個名為 player_card 的列表供玩家查看。 這里是參考。
list_of_suits= [] #Creating list of cards
player_card = []
king_of_spades = 10 #Creating face cards for the spades deck.
queen_of_spades = 10
jack_of_spades = 10
king_of_clubs = 10
queen_of_clubs = 10
jack_of_clubs = 10
king_of_hearts = 10
queen_of_hearts = 10
jack_of_hearts = 10
king_of_diamonds = 10
queen_of_diamonds = 10
jack_of_diamonds = 10
ace_of_spades = [1,11] # Aces are either 1 or 11
ace_of_clubs = [1,11]
ace_of_hearts = [1,11]
ace_of_diamonds = [1,11]
spades = [ace_of_spades,2,3,4,5,6,7,8,9,10, jack_of_spades, queen_of_spades, king_of_spades]
clubs = [ace_of_clubs,2,3,4,5,6,7,8,9,10, jack_of_clubs, queen_of_clubs, king_of_clubs]
hearts = [ace_of_hearts,2,3,4,5,6,7,8,9,10, jack_of_hearts, queen_of_hearts, king_of_hearts]
diamonds = [ace_of_diamonds,2,3,4,5,6,7,8,9,10, jack_of_diamonds, queen_of_diamonds, king_of_diamonds]
list_of_suits.append(spades)
list_of_suits.append(clubs)
list_of_suits.append(hearts)
list_of_suits.append(diamonds)
這是隨機卡片的選擇器。 它將遍歷數組以隨機選擇四張卡片中的一張。 接下來,它將進入該數組並隨機選擇一張卡片。
random_list_of_suits = random.choice(list_of_suits)
random_card_number = random.choice(random_list_of_suits)
random_list_of_suits.remove(random_card_number)
player_card.append(random_card_number)
print player_card
print list_of_suits
這是我想要弄清楚的:如何每次創建一個新的隨機數?
我有點卡住了,我嘗試將它放入 for 循環,但是如果我將 random_card_number 放入循環中,它將選擇與最初四次相同的隨機卡片。
import random
list2d = [range(0, 5), range(5, 10), range(10, 15), range(15, 20)]
for i in range(0, 10):
random_suite = random.choice(list2d)
random_card = random.choice(random_suite)
print random_suite, random_card
輸出:
[5, 6, 7, 8, 9] 7
[5, 6, 7, 8, 9] 5
[5, 6, 7, 8, 9] 5
[10, 11, 12, 13, 14] 11
[10, 11, 12, 13, 14] 13
[10, 11, 12, 13, 14] 12
[10, 11, 12, 13, 14] 14
[10, 11, 12, 13, 14] 10
[10, 11, 12, 13, 14] 10
[0, 1, 2, 3, 4] 2
您在 random.choice() 中輸入的列表必須是一維數組。 所以你可以這樣做,
random_list_of_suits = np.random.choice(list_of_suits) # you can get spades/clubs/hearts/diamonds
index_of_random_card_number = random.choice(len(random_list_of_suits))
random_card = random_list_of_suits[index_of_random_card_number] # You get a random card
#include <stdafx.h>
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()
using namespace std;
int main()
{
srand(time(0)); // set initial seed value to system clock
for (int nCount=0; nCount < 100; ++nCount)
{
cout << rand() << "\t";
if ((nCount+1) % 5 == 0)
cout << endl;
}
srand 使用時間作為第一個初始種子來創建您的隨機數,因此每次運行程序時,您將獲得不同的隨機數,因為初始種子將隨時間變化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.