0

我正在尝试使用以下代码列出一副卡片中的每张卡片(以及分配给卡片的编号):

suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")

def translate():
    rank = ""
    suit = ""
    cards = ""
    cardNum = 0

    for x in rankName:
        rank = x

    for y in suitName:
        suit = y

    for i in range(0, NUMCARDS):
        cards += rank
        cards += " of "
        cards += suit
        cardNum = i
        i += 1

        print cardNum
        print "    "
        print cards

不过,我的输出只获得了 52 次“俱乐部之王”。我需要做什么?

4

2 回答 2

3

还有一些内置的方法可以完成你想要的。

import itertools

suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")

cross_product = itertools.product(rankName, suitName)

for card_num, (rank, suit) in enumerate(cross_product, start=1):
  print("{0}    {1} of {2}".format(card_num, rank, suit))
于 2013-06-14T23:16:15.387 回答
2

您的循环应该是嵌套的,但现在它们只是按顺序执行。现在,rank遍历所有rankNames 并设置为最后一个,suit遍历所有suitNames 并设置为最后一个,然后将它们打印 52 次。

你甚至不应该有最后一个循环。

suitName = ("hearts", "diamonds", "spades", "clubs")
rankName = ("Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King")

def translate():
    cardNum = 0

    for x in rankName:
        rank = x

        for y in suitName:
            suit = y

            cards = ""
            cards += rank
            cards += " of "
            cards += suit
            i += 1

            print cardNum
            print "    "
            print cards

此外,rank = xandsuit = y可能只是for rank in rankName:and for suit in suitName。此外,预初始化变量也不是很有用。

于 2013-06-14T22:57:14.187 回答