从一副牌中生成52张随机牌而不会出现重复

时间:2018-02-08 04:15:33

标签: python random

这是我到目前为止所提出的:

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次,但我最终得到重复。我怎么能避免这个?

3 个答案:

答案 0 :(得分:4)

如果您不需要二维数组,则可以更简单地执行此操作。如果您只有一个平面列表,则可以使用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用于随机化卡片列表,这样您就可以在列表末尾迭代/拉出卡片。

答案 1 :(得分:1)

import random
import itertools as it


deck = list(it.product("♠♣♥♦", [str(x) for x in range(2, 11)] + list("JQKA")))
random.shuffle(deck)

print(len(deck))
print(deck)
# 52
# [('♠', '6'), ('♦', 'J'), ('♣', '4'), ('♣', '7'), ('♠', '8'), ('♦', 'K'), ...]

或者,使用集合:

deck = set(it.product("♠♣♥♦", {str(x) for x in range(2, 11)} | set("JQKA")))

答案 2 :(得分:0)

使用memoization helper将值放入集合中,如果值在集合中,则不会添加它并选择另一张随机卡,直到所有52张卡都在选项列表中。因此处理任何重复

import random
import itertools as it

deck = list(it.product("♠♣♥♦", [str(x) for x in range(2, 11)] + list("JQKA")))
random.shuffle(deck)

# print(len(deck))
# print(deck)

memo = set()  
def deal(n):

    for i in range(n):
        k = random.choice(deck)
        if k not in memo:
            memo.add(k)
        else:
            deal(1)
    print(len(memo))
    return memo           

print(deal(52))

你可以做到

return sorted(memo)

这将返回一个排序列表,以便于视觉确认