我试图在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放在一个循环中,它将选择它最初做了四次的相同随机卡。
答案 0 :(得分:0)
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
答案 1 :(得分:0)
您在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
答案 2 :(得分:-5)
#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使用时间作为第一个初始种子来创建随机数,因此每次运行程序时,您将获得不同的随机数,因为进样种子将随时间变化。