打印列表与玩家数量(二十一点)

时间:2016-02-02 22:45:05

标签: python python-3.x

所以我正在写一个二十一点程序,但我被困在一个部分(这是杀了我arrghh)。

我正在尝试用相应的玩家打印多手牌(列表)。

pHands = [['9D','2H'],['TS','2D]等。]#这只是一个洗牌的甲板

离。玩家n:[3H,TS]

以下是代码:

def print_blackjack(pHands, num_of_players):
    for i in pHands:
        for num in range(num_of_players):
            print('Player' + str(num) + ':', i)
    return

它会返回双手,但是每只手都有多个与之相关的玩家。

我知道这是一个简单的问题,但我的想法是给我一个空白。

有任何帮助吗?谢谢!

编辑***这是迄今为止的完整代码

def make_deck():
    # Randomly shuffle a deck
    import random
    cards = []
    for suit in ['H', 'C', 'S', 'D']:
        for num in ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q',
                'K']:
            cards.append(num + suit)
    random.shuffle(cards)
    return cards
deck = make_deck()


num_of_players = int(input("How many players?: "))

def deal_blackjack(deck, num_of_players):
    # Deal two cards to a number of players
    hands = [[] for p in range(num_of_players)]
    i = -1
    for k in range(0,2):
        for h in hands:
            i += 1
            h.append(deck[i])
    return hands

pHands = deal_blackjack(deck, num_of_players)


def print_blackjack(pHands, num_of_players):
    print(list(enumerate(pHands)))
    return

4 个答案:

答案 0 :(得分:1)

应该是:

def print_blackjack(pHands):
    for i in range(len(pHands)):
        print('Player', i, ':', pHands[i])

答案 1 :(得分:1)

您根本不需要参数 num_of_players :您已经从手册列表的大小知道了这一点。试试这个:

对于我,输入枚举(pHands):         print' Player',i,':',hand

答案 2 :(得分:1)

如果你想在你的打印中将玩家n与pHands [n]联系起来,你可以这样做:

def print_blackjack(pHands, num_of_players):
    for i in range(num_of_players):
        print('Player' + str(i) + ':', pHands[i])

注意:@TomKarzes写道,你最后不需要 return

答案 3 :(得分:0)

正如@Rogalski指出的那样,您可以使用enumerate函数从pHands列表中生成(数字,数据)对。

试试这个。

def show_hands(hands):
    for num, hand in enumerate(hands):
        print("Player {}: {}".format(num, hand))

输出看起来像这样。

Player 0: ['9D', '2H']
Player 1: ['TS', '2D']