英文:
How can I create a list of tuples representing a deck of cards?
问题
我试图创建一副扑克牌的牌组,其中每张牌都是一个元组。例如,价值为11的牌'红心A'将是(A
, ♥
, 11)。如何生成整副牌组并将其保存在列表中,而不使用类?
英文:
I am trying to make a deck of playing cards,where each is a tuple. For example, the card 'Ace of Hearts' with value of 11 would be (‘A’, ‘♥’, 11)
.
How can I generate the entire deck without using classes and save it in a list?
答案1
得分: 0
使用静态定义的花色、牌和点数,您可以按照以下方式使用列表推导来获取一组牌 - 然后,牌组列表包含表示牌的元组。您可能希望根据您的要求更改如何定义点数列表。
suits = ['♠', '♥', '♦', '♣']
cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
values = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
deck = [(c, s, v) for c, v in zip(cards, values) for s in suits]
英文:
Using static definitions for the suits, cards, and values, you can do the following to get a list of cards using a list comprehension - the deck list then contains tuples representing cards. You may want to change how the values list is defined according to your requirements.
suits = ['♠', '♥', '♦', '♣']
cards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
values = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
deck = [(c, s, v) for c, v in zip(cards, values) for s in suits]
答案2
得分: 0
你可以使用collections.namedtuple
,但我认为在这里使用类(特别是Enum.enum
)更合适:
from collections import namedtuple
Card = namedtuple("Card", ["rank", "suit"])
cards = []
for suit in "\u2660", "\u2665", "\u2666", "\u2663":
for rank in "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K":
cards.append(Card(rank, suit))
print(cards)
英文:
You could use a collections.namedtuple
, but I do think classes (especially Enum.enum
s are the way to go here):
from collections import namedtuple
Card = namedtuple("Card", ["rank", "suit"])
cards = []
for suit in "\u2660", "\u2665", "\u2666", "\u2663":
for rank in "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K":
cards.append(Card(rank, suit))
print(cards)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论