gpt4 book ai didi

python - 如何从二维列表中选择一个随机元素

转载 作者:太空宇宙 更新时间:2023-11-04 06:44:30 24 4
gpt4 key购买 nike

我试图在 python 的二维列表中选择一个随机元素。我正在创建一个二十一点游戏。

I'm aware of how long and non-optimized this code is, but I'm new to programming and I want to make mistakes to learn.

Here's the initial code that I have set up. I create the suits (spades, clubs, hearts, diamonds). I append it to the list called list_of_cards which was initialized as an empty array.

Then I have another list called player_card for the player to view. Here it is in reference.

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)

This is the selector for a random card. It will iterate through the array to select one of the four cards randomly. Next, it will go into that array and choose a random card.

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

Here's what I'm trying to figure out: How do I create a new random number each time?

I'm kind of stuck and I tried putting it through a for loop, but if I put the random_card_number in a loop, it will select the same random card that it did initially four times.

最佳答案

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

关于python - 如何从二维列表中选择一个随机元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28908080/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com