Skip to main content
 首页 » 编程设计

python之从一副纸牌中生成 52 张随机纸牌而不重复

2025年05月04日21qlqwjy

这就是我到目前为止的想法:

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用于随机化卡片列表,这样您就可以迭代/拉出列表末尾的卡片。