【问题标题】:Printing random cards (Python)打印随机卡片(Python)
【发布时间】:2016-10-26 04:50:09
【问题描述】:

我正在编写一个程序来处理一副纸牌。我需要随机处理它们。我只是不确定随机打印它们。 这是我到目前为止的代码..

import random


def create_deck():
    for i in range(10):
        pip = random.choice(PIPS)
        suit = random.choice(SUITS)
        card = (pip, suit)


def deal_deck(DECK):
    for pip in PIPS:
        for suit in SUITS:
            print(pip + suit,end=" ")
        print()

CLUB = "\u2663"
HEART = "\u2665"
DIAMOND = "\u2666"
SPADE = "\u2660"

PIPS = ("A","2","3","4","5","6","7","8","9","10","J","Q","K")
SUITS = (CLUB, SPADE, DIAMOND, HEART)
DECK= []

create_deck
deal_deck(DECK)

【问题讨论】:

  • 将所有 52 张卡片放在一个列表中,然后 shuffle 它。
  • 您是否考虑过为卡片创建一个类而不是使用元组?
  • 这实际上是一个作业,我被指示使用元组,我们还没有涵盖类。
  • @H.Soto 没关系。我只是问问罢了。你不需要。使用类只是面向对象多一点。

标签: python-3.x random


【解决方案1】:

这是一个如何生产和洗牌的示例。

from itertools import product
from random import shuffle 
all_cards = list(product(PIPS, SUITES))

shuffle(all_cards)

just_10_cards = all_cards[:10]
for p, suite in just_10_cards:
    print(p, suite, end='')
print()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    相关资源
    最近更新 更多