Skip to main content
 首页 » 编程设计

python之如何使用for循环打印卡片

2025年05月04日13lidabo

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

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 

请您参考如下方法:

您的函数 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)