这可能是一个愚蠢的问题,但是我创建了一个矩阵,其中包含从一副纸牌中随机生成的值:
ranks = ['A',2,3,4,5,6,7,8,9,10,'J','Q','K']
suits = ['♠', '♥', '♣', '♦']
deck = []
for rank in ranks:
for suit in suits:
card = str(rank) + suit
deck.append(card)
random.shuffle(deck)
matrix = [[[random.choice(deck), ''] for i in range(13)]for j in range(4)]
,并希望添加一种方法,该方法通过仅返回卡的值来“翻转”卡:
def get_card(row, col):
print(matrix[row][col][0])
我将如何更改此代码,以使在矩阵中创建的值保持不变?每次调用get_card(1,2)时,它都会返回一个不同的随机生成的值。
再次表示抱歉,如果这是一个愚蠢的问题,在此先感谢您的帮助或建议。
答案 0 :(得分:3)
只要不重新创建矩阵,该矩阵就为常数。请参见下面的示例:
import random
matrix = None
def create_deck():
ranks = ['A',2,3,4,5,6,7,8,9,10,'J','Q','K']
suits = ['♠', '♥', '♣', '♦']
deck = []
for rank in ranks:
for suit in suits:
card = str(rank) + suit
deck.append(card)
random.shuffle(deck)
global matrix
matrix = [[[random.choice(deck), ''] for i in range(13)]for j in range(4)]
def get_card(row, col):
print(matrix[row][col][0])
# First deck, get_card returns the same value
create_deck()
for _ in range(5):
get_card(1,2)
# Create new deck, get_card returns the same value, but not the same as before
create_deck()
for _ in range(5):
get_card(1,2)
输出(在我的奔跑中,您将拥有不同的牌但模式相同):
J♥
J♥
J♥
J♥
J♥
5♠
5♠
5♠
5♠
5♠