如何创建一个表示一副扑克牌的元组列表?

huangapple go评论79阅读模式
英文:

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.enums 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)

huangapple
  • 本文由 发表于 2020年1月6日 23:37:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定