Python 3.x:将卡片交给x数量的玩家并制作列表的功能

时间:2018-01-29 20:21:04

标签: python python-3.x

到目前为止,我有这个:

def make_deck():
    deck = []

for suit in "HDSC":
        for rank in "JQKA23456789T":
            deck.append(rank + suit)

    random.shuffle(deck)

    return deck

def cards(deck, number_players): # What should I do for this function?
    deck = make_deck()


    for i in range:
        hands = []
        player_hand = [deck.pop(), deck.pop()]

    return hands

我应该生成如下所示的输出:

hands = cards(deck, 3)
print(hands)
[['5H', '3H'], ['5S', '4S'], ['7H', '4H']]

因此,用户可以确定打印了多少张卡片。

2 个答案:

答案 0 :(得分:2)

我看到下面代码中提到的一些错误:

def make_deck():
    deck = []

    for suit in "HDSC":
        for rank in "JQKA23456789T":
            deck.append(rank + suit)

    random.shuffle(deck)
    return deck

def cards(deck, number_players):
    hands = []  # define hands outside of the for loop
    for i in range(number_players):  # You need to specify a range
        hands.append([deck.pop(), deck.pop()])  # give each player a hand size of 2
    return hands

# finally put it all together by creating a new deck and passing it into cards()
cards(make_deck(), number_players)

我尽力直觉该计划的目的。这是你在找什么?

答案 1 :(得分:1)

您可以尝试这一点,并且在您定义的函数cards()中,deck参数是多余的。但是如果你想让套牌可以改变,你可以重写代码。

import random

def make_deck():

   deck = []

   for suit in "HDSC":
    for rank in "JQKA23456789T":
        deck.append(rank + suit)

   random.shuffle(deck)

   return deck

def cards(number_players): 

   deck = make_deck()
   hands = []

   for i in range(number_players):

     hands.append([deck.pop(), deck.pop()])

   return hands

召回功能:

hands = cards(3)

print(hands)