1

我已经设置了所有 52 张卡片,我尝试使用for loop. 我现在不知道如何设置我for loop的。

def define_cards(n):
    rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
    suit_string = ("clubs","diamonds","hearts","spades")
    cards = []
    for suit in range(4):
        for rank in range(13):
            card_string = rank_string[rank] + " of " + suit_string[suit]
            cards.append(card_string)

print "The cards are:"
for i in range(52):              #how to make this for loop work??
    print i, card_string[i]

我想这样打印

The crads are:
0 ace of clubs
1 two of clubs
2 three of clubs
...
49 jack of spades
50 queen of spades
51 king of spades
4

5 回答 5

4

您的函数define_cards必须返回列表。return cards在其末尾添加。

然后你必须实际调用/执行这个函数。

然后您可以访问此列表中的各个卡片:

cards = define_cards()
for i, card in enumerate(cards):
    print i, card

但是,如果您正在寻找“更 Pythonic”的解决方案,请尝试以下操作:

import itertools as it

rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
suit_string = ("clubs","diamonds","hearts","spades")

print 'The cards are:'
for i, card in enumerate(it.product(rank_string, suit_string)):
    print i, '{0[1]} of {0[0]}'.format(card)
于 2011-05-05T09:45:30.133 回答
2

只看这个

    cards.append(card_string)

print "The cards are:"
for i in range(52):              #how to make this for loop work??
    print i, card_string[i]

为什么要打印card_string[i]

有什么问题cards[i]

于 2011-05-05T09:46:07.640 回答
1

为什么不使用迭代器:

def define_cards():
    rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
    suit_string = ("clubs","diamonds","hearts","spades")
    for suit in suit_string:      # you can obtain the items of the iterate list directly, no need of rank access
        for rank in rank_string:
            card_string = rank + " of " + suit
            yield card_string

print "The cards are:"
cards_iterator = define_cards()
for i, card in enumerate(cards_iterator):   # use the iterator power ;)
    print i, card
于 2011-05-05T09:43:59.780 回答
1
ranks = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
suits = ("clubs","diamonds","hearts","spades")

答案是优雅的单线:

cards = [rank+' of '+suit for suit in suits for rank in ranks]

for i,card in enumerate(cards):
    print i, card

结果:

0 ace of clubs
1 two of clubs
...
50 queen of spades
51 king of spades
于 2011-05-05T09:49:40.697 回答
1
def define_cards():
    rank_string = ("ace","two","three","four","five","six","seven","eight","nine","ten","jack","queen","king")
    suit_string = ("clubs","diamonds","hearts","spades")
    cards = []
    n = 0
    for suit in suit_string:
        for rank in rank_string:
            print '%s %s of %s' % (n,rank,suit)
            n+=1

define_cards()
于 2011-05-05T09:52:39.550 回答