我需要能够在洗牌后对牌组进行排序。我的想法是将列表分解回它的两个组件,并检查每个组件是否有序,然后将它重新组合在一起。
如何从Deck类内部分别访问值部分和套装部分?
如果你对如何做到这一点有更好的了解,我也会很感激。
由于列表中的项目是char + int即(' 2C',' KH'),.sort()
调用将无效。
import random
class Card:
def __init__(self, suit, order):
self.order = order
self.suit = suit
def fan(self):
print(self.order, "of", self.suit)
class Deck():
def __init__(self):
self.deck = []
for suit in ['Clubs', 'Diamonds', 'Hearts', 'Spades']:
for order in ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']:
self.deck.append(Card(suit, order))
def fan(self):
for c in self.deck:
c.fan()
def shuffle(self):
for suit in ['Clubs', 'Diamonds', 'Hearts', 'Spades']:
for order in ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']:
self.deck.append(Card(suit, order))
random.shuffle(self.deck)
def deal(self):
return self.deck.pop()
def isOrdered(self):
pass
def Order(self):
pass
答案 0 :(得分:0)
"教"卡片对象如何相互比较:
sort()
方法要求卡片对象必须至少能够回答&#34;问题card1 < card2
所以Card
类需要一个额外的方法:
def __lt__(self, other):
"""
Returns self < other
"""
# Following two should better be defined globally (outside of method
# and maybe outside of the Card class
SUIT_LIST = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
ORDER_LIST = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
if self.suit == other.suit:
return ORDER_LIST.index(self.order) < ORDER_LIST.index(other.order)
else:
return SUIT_LIST.index(self.suit) < SUIT_LIST.index(other.suit)
现在可以将卡片对象与<
进行比较,并且可以对卡片对象列表进行排序。