为了账号安全,请及时绑定邮箱和手机立即绑定

将类的新实例添加到列表中?

将类的新实例添加到列表中?

MYYA 2023-04-11 16:26:27
我正在学习 Python 并且正在构建纸牌游戏(似乎很常见并且对初学者来说很好)。我有一个名为打印随机卡的Cartas 方法的类。imprimir()然后我有一个名为的函数create_deck(),它用 52 张卡片填充一个空列表。import randomclass Cards:    def __init__(self, Value = random.choice([1,2,3,4,5,6,7,8,9,10,11,12,13]),                        Suit = random.choice(["Diamonds", "Hearts", "Clubs", "Spades"])):        self.Value = Value        self.Suit = Suit    def imprimir(self):        if self.Value == 11:            print("J of " + self.Suit)        elif self.Value == 12:            print("Queen of " + self.Suit)        elif self.Value == 13:            print("King of " + self.Suit)        else:            print(str(self.Value) + " de " + self.Suit)card = Cards()card.imprimir()def create_deck():    list_deck = []    list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]    lista_suit = ["Diamonds", "Hearts", "Clubs", "Spades"]    for number in list_numbers:        for suit in list_suit :            if card == 11:                card = f'J of {suit}'                list_deck.append(card)            elif number == 12:                card = f'Queen of {suit}'                list_deck.append(card)            elif number == 13:                card = f'King of {suit}'                list_deck.append(card)            else:                card = f'{number} of {suit}'                list_deck.append(card)    print(list_deck)print(create_deck())我想create_deck()用 的新实例填充空列表,Cards()而不是只用字符串填充它,例如: [card1, card2, card3, etc etc,..card52]。我怎样才能做到这一点?
查看完整描述

2 回答

?
呼唤远方

TA贡献1856条经验 获得超11个赞

除了 for 循环,您还可以使用列表推导式在一行中完成:


list_deck = [Cards(num, suit) for num in list_numbers for suit in list_suit]

如果您更喜欢像以前一样使用 for 循环,那么只需使用您的类将项目添加到列表中:


for number in list_numbers:

    for suit in list_suit :

        list_deck.append(Cards(number, suit))

如果你想打印你的 Cards 对象,那么你需要为你的类实现repr函数。


def __repr__(self):

    if self.Value == 11:

        return("J of " + self.Suit)

    elif self.Value == 12:

        return("Queen of " + self.Suit)

    elif self.Value == 13:

        return("King of " + self.Suit)

    else:

        return(str(self.Value) + " de " + self.Suit)


查看完整回答
反对 回复 2023-04-11
?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

你可以这样生成它:

cards = [Cards() for card in range(n_cards)]

这样,对于可迭代对象中的每个元素range(n_cards)(它只是从 0 到独占 n_cards (0, 1, 2... n_cards - 1) 的范围),您将向Cards()列表中添加一个新对象。


查看完整回答
反对 回复 2023-04-11
  • 2 回答
  • 0 关注
  • 95 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信