I'm making a game in python with a deck of cards. I have an array of the cards I've created, and shuffled. I would like to be able to sort this array, both by value: {2,3,4,5,6,7,8,9,10,J,Q,K,A} and by their suit and corresponding values - same order of values. I have previously used the sort and sorted methods, however am unsure how to do this with an array of objects as I am getting the output: TypeError: 'Card' object is not subscriptable. How would I go about creating these sorting algorithims?
I have tried the following: self.cards.sort(key=lambda x: x.value) This sorts it the the order: {10,2,3,4,5,6,7,8,9,A,J,Q,K} I understand the alphabetical order this is sorted in, however am unsure why 10 is the first item listed.
I have also tried things like: values=dict(zip('23456789TQKA',range(2,15))) but this seems to give me the error I have previously talked about.
Any help would be apricated! Thanks!
This is the code I currently have:
from random import randint
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def show(self):
print("{} - {}".format(self.value, self.suit))
class Deck:
size = 52
def __init__(self):
self.cards = []
self.build()
def build(self):
for s in ["C", "D", "H", "S"]:
for v in ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]:
self.cards.append(Card(s, v))
def show(self):
for c in self.cards:
c.show()
def shuffle(self):
for i in range(self.size-1, 0, -1):
r = randint(0, i + 1)
self.cards[i], self.cards[r] = self.cards[r], self.cards[i]
#Sorting will go here
deck = Deck()
print("After creating The Deck")
deck.show()
deck.shuffle()
print("After Shuffling The Deck: ")
deck.show()
deck.mergeSort()
print("After the merge Sort")
deck.show()