I know this has been asked before, but I'm looking for a cleaner solution if there is one. I want to sort a hand of cards by suit and order.
Here's is the pertinent part of my Deck class:
import card
import random
class Deck:
def __init__(self):
suits = ["Hearts", "Diamonds", "Clubs", "Spades"]
values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" ,"A"]
self._cards = [card.Card(suit, value) for suit in suits for value in values]
def deal_hand(self):
hand = random.sample(self._cards, 5)
for card in hand:
self._cards.remove(card)
hand.sort(key=lambda x: (x.suit, x.value))
return hand
Here's my card class:
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def __repr__(self):
return f"{self.value} of {self.suit}"
However, when I look at the players' hands, they are only sorted by suit, and not by value.
Here is the output I'm getting:
John's hand: [10 of Clubs, 2 of Clubs, A of Hearts, 9 of Spades, J of Spades]
Arnold's hand: [K of Clubs, 8 of Diamonds, 7 of Hearts, 9 of Hearts, 7 of Spades]
Alex's hand: [Q of Clubs, 2 of Hearts, 5 of Hearts, 8 of Spades, K of Spades]
Morgan's hand: [5 of Clubs, A of Diamonds, 10 of Hearts, Q of Hearts, 2 of Spades]
Where 10 of Clubs comes before 2 of Clubs. Also, K of x will come before Q of x.
Why is my lambda only sorting by suit? I would at least expect 10 of Clubs to come after 2 of Clubs.
Is there a clean solution?