2017-12-03 73 views
0

我需要能夠在洗牌後對卡座進行分類。我的想法是將列表重新分成兩個組件,並檢查每個組件是否有序,然後重新組合。卡片組訂購

如何從Deck類內部分別訪問價值部分和適合部分?

如果你對如何做到這一點有個更好的想法,我也會很感激。

.sort()由於列表中的項是char + int,即('2C','KH'),調用將不起作用。

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 
+1

目前還不清楚你想要什麼。排序甲板?什麼意思是「混合型入門」?爲了允許對卡片進行排序,您應該爲其定義比較運算符('__gt__','__lt__',...)或計算每張卡片的主要值(主要是' * 13 + '),並將此計算函數用作關鍵字函數在'sort()' –

+0

'Deck.deck'列表中的項目是'Card'對象。或者你的意思是不同的列表? –

+0

@MichaelButscher我想要在'deck'列表中訂購'card'對象。這是否更有意義? – Jonathan

回答

0

「教」的卡對象如何互相比較:

sort()方法要求的卡對象必須能夠至少「答案」的問題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) 

現在卡對象可以<進行比較和卡的對象列表進行排序。

+1

您不需要'SUIT_LIST'的'index'方法;這四套西裝已經按字母順序排列。 – chepner

+0

@chepner好的,但是如果稍後需要不同的花色順序,這更通用。 –