如何使用for循环打印卡片?

1 投票
5 回答
2236 浏览
提问于 2025-04-16 17:02

我已经准备好了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

5 个回答

1

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这些问题可能是因为我们写的代码有bug,或者是因为我们没有正确理解某些概念。

当我们在网上寻找解决方案时,像StackOverflow这样的网站就非常有用。这里有很多程序员分享他们的经验和解决方案,帮助其他人解决类似的问题。

如果你在学习编程,遇到困难,不妨去这些论坛看看,可能会找到你需要的答案。同时,记得多尝试,多实践,编程的技能就是在不断的尝试中提升的。

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()
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] 有什么问题吗?

4

你的函数 define_cards 需要返回一个列表。在它的最后加上 return cards

然后你需要真正地调用这个函数,让它执行。

这样你就可以访问这个列表中的每一张卡片了:

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

不过,如果你想要一个“更符合Python风格”的解决方案,可以试试这个:

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)

撰写回答