到目前为止,这是我提出的:
import time
from random import randint
Suits = [
["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Joker", "Queen", "King"], #hearts
["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Joker", "Queen", "King"], #clubs
["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Joker", "Queen", "King"], #spades
["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Joker", "Queen", "King"] #diamonds
]
for x in range(0,52):
#selection of random card and suit
Suit = randint(0,3)
Card = randint(0,12)
# prints what card was received from the deck
if Suit == 0:
print("You got a", Suits[0][Card], "of Hearts")
elif Suit == 1:
print("You got a", Suits[1][Card], "of Clubs")
elif Suit == 2:
print("You got a", Suits[2][Card], "of Spades")
else:
print("You got a", Suits[3][Card], "of Diamonds")
这使我可以从一副纸牌中生成一张随机纸牌53次,但最终却得到了重复。我将如何避免这种情况?
最佳答案
如果您确实不需要二维数组,则可以更简单地执行此操作。如果您只有一个平面列表,则可以使用Python的random库轻松完成此操作:
import random
cards = [(s, v) for s in ['H', 'S', 'C', 'D']
for v in [str(i) for i in range(2, 11)] + list("JKQA")]
random.shuffle(cards)
列表推导用于将
cards
设置为具有西服和等级组合的元组。然后使用random.shuffle
来随机化就位卡列表,以便您可以迭代/拉出列表末尾的卡。关于python - 从一副纸牌中生成52张随机纸牌,而不会产生重复,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48677430/