How can I sort card list by type first then by value ? for eg: the player1 cards should be sorted like this: 2 clubs , 3 clubs , 6 clubs , 5 heart, 10 heart ....etc I've read some search about lambda function but the result is not what I need any help?
from enum import Enum
import random
type=Enum('type','Heart Diamond Club Spade')
value=Enum('value','2 3 4 5 6 7 8 9 10 J Q K A')
class Card():
def __init__(self,type,value) :
self.card_type=type
self.card_value=value
def __str__(self) :
txt=str(self.card_value.name) ' ' str(self.card_type.name)
return txt
def __eq__(self, __o: object) -> bool:
if self.card_type==__o.card_type and self.card_value==__o.card_value:
return True
else:
return False
def __lt__(self,__o:object) -> bool:
if self.card_type==__o.card_type and int(self.card_value.value)<int(__o.card_value.value):
return True
else:
return False
def __gt__(self,__o:object) -> bool:
if self.card_type==__o.card_type and int(self.card_value.value)>int(__o.card_value.value):
return True
else:
return False
def deal(deck,cardNum):
cardlist=list()
for i in range(cardNum):
c=random.choice(deck)
deck.remove(c)
cardlist.append(c)
#sorted(cardlist,key=lambda ) # My problem is here :(
return cardlist
CodePudding user response:
If I understand you correctly, what you want is "human sort"? If not, please share what's the "inputs" looks like then.
Try this natsort lib:
>>>import natsort
>>>cards = " 2 clubs, 1 heart, 10 heart, 3 clubs, 9 clubs"
>>>natsort.natsorted(cards.split(','))
[' 1 heart', ' 2 clubs', ' 3 clubs', ' 9 clubs', ' 10 heart']