class Deck:
    def __init__(self):
        ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
        suits = ['C', 'D', 'H', 'S'] 
        self.cards = []
        for s in suits:
            for r in ranks:
                self.cards.append(Card(r,s))
    
    def __str__(self):
        return str([str(card) for card in self.cards])

    def draw(self):
        return self.cards.pop()   
    
    def shuffle(self):
        random.shuffle(self.cards)
    
    def deal(self,n):
        deal =[]
        for i in range(n):
            deal.append(self.cards.pop())
            
        return deal
d=Deck()
print(d.deal(5))

output:
[<__main__.Card object at 0x0000013493F816D0>, <__main__.Card object at 0x0000013493F81100>, <__main__.Card object at 0x0000013493F82160>, <__main__.Card object at 0x0000013493F818B0>, <__main__.Card object at 0x0000013493F6FF40>]

Kode saya mencetak informasi data..

Saya tidak tahu di mana saya melakukan kesalahan dalam kode.

Juga, apakah ada cara untuk mendapatkan hasil yang lebih baik untuk dek?

Saya ingin dek saya dicetak di cangkang seperti ini

Bagus dan terorganisir. Terima kasih sebelumnya

 2 C, 3 C, 4 C, 5 C, 6 C,
 7 C, 8 C, 9 C, T C, J C,
     ....
 J S, Q S, K S, A S
1
Trap House 12 Mei 2021, 08:00

1 menjawab

Jawaban Terbaik

Anda dapat mengganti metode kartu str seperti ini

import random


class Card:
    def __init__(self, r, s):
        self.r = r
        self.s = s

    def __str__(self):
        return "{} {}".format(self.r, self.s)


class Deck:
    def __init__(self):
        ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
        suits = ["C", "D", "H", "S"]
        self.cards = []
        for s in suits:
            for r in ranks:
                self.cards.append(Card(r, s))

    def __str__(self):
        return str([str(card) for card in self.cards])

    def draw(self):
        return self.cards.pop()

    def shuffle(self):
        random.shuffle(self.cards)

    def deal(self, n):
        deal = []
        for i in range(n):
            deal.append(str(self.cards.pop()))

        return deal


if __name__ == "__main__":
    d = Deck()
    print(", ".join(d.deal(5)))
0
Sreevardhan Reddy 12 Mei 2021, 05:12