python 为什么我不能把数字转换成卡片中的字符串?

xt0899hw  于 2023-06-28  发布在  Python
关注(0)|答案(2)|浏览(149)

所以我一直在为学校的一个项目开始制作一副卡片,所以我必须沿着使用这些循环制作一副卡片的过程。我尝试将2到10之间的所有数字转换为字符串,以便创建它们的卡片:

suits = ["♥", "♦", "♣", "♠"]
deck = []

for suit in suits:
    for card in range(1,14):
        if card == 1:
            deck.append("A" + suit)
        elif card == 11:
            deck.append("J" + suit)
        elif card == 12:
            deck.append("Q" + suit)
        elif card == 13:
            deck.append("K" + suit)
        else:
            str(card)
            deck.append(card + suit)
print (deck)

但是,我有一个错误,它是如下:

Traceback (most recent call last):
  File "(removed for privacy reasons)", line 16, in <module>
    deck.append(card + suit)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

有人能解释我做错了什么吗?
我期待一个输出:
[A♥, 2♥, 3♥, 4♥, 5♥, 6♥, 7♥, 8♥, 9♥, 10♥, J♥, Q♥, K♥, A♦, 2♦, etc etc etc]

pbgvytdp

pbgvytdp1#

您没有将转换后的字符串存储在此行str(card)的任何位置。
已将代码更新为

suits = ["♥", "♦", "♣", "♠"]
deck = []

for suit in suits:
    for card in range(1,14):
        if card == 1:
            deck.append("A" + suit)
        elif card == 11:
            deck.append("J" + suit)
        elif card == 12:
            deck.append("Q" + suit)
        elif card == 13:
            deck.append("K" + suit)
        else:
            card = str(card)
            deck.append(card + suit)
print (deck)

它输出

['A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥', 'A♦', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦', 'A♣', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣', 'A♠', '2♠', '3♠', '4♠', '5♠', '6♠', '7♠', '8♠', '9♠', '10♠', 'J♠', 'Q♠', 'K♠']
vfh0ocws

vfh0ocws2#

您可以通过明智地使用字典来消除条件检查并使代码更加紧凑,如下所示:

suits = ["♥", "♦", "♣", "♠"]
deck = []
hcards = {
    1: 'A',
    11: 'J',
    12: 'Q',
    13: 'K'
}

for suit in suits:
    for card in range(1, 14):
        deck.append(f'{hcards.get(card, card)}{suit}')

print(deck)

输出:

['A♥', '2♥', '3♥', '4♥', '5♥', '6♥', '7♥', '8♥', '9♥', '10♥', 'J♥', 'Q♥', 'K♥', 'A♦', '2♦', '3♦', '4♦', '5♦', '6♦', '7♦', '8♦', '9♦', '10♦', 'J♦', 'Q♦', 'K♦', 'A♣', '2♣', '3♣', '4♣', '5♣', '6♣', '7♣', '8♣', '9♣', '10♣', 'J♣', 'Q♣', 'K♣', 'A♠', '2♠', '3♠', '4♠', '5♠', '6♠', '7♠', '8♠', '9♠', '10♠', 'J♠', 'Q♠', 'K♠']

相关问题