1.一摞紙牌示例
import collections as cl
import random as rd
card=cl.namedtuple('card',['point', 'suit'])
class cards():
points=[str(n) for n in range(2,11)]+list('JQKA')#列表可以使用加法拼接
suits='spades diamonds clubs hearts'.split()#str中的split函數默認以空格對字符串進行切片,返回一個列表,列表中的每個元素都是一個字符串
print(points)
print(suits)
def __init__(self):
print('__init__ is called')
self.allcards=[card(point, suit)
for point in self.points for suit in self.suits]#使用列表生成式填充card的point和suit,從而初始化allcards
def __len__(self):
print('__len__ is called')
return len(self.allcards)
def __getitem__(self,pos):
print('__getitem__ is called')
return self.allcards[pos]
2.collection中的namedtuple方法用來定義card類,card類中的屬性爲point和suit
card1=card('7', 'spades')
print(card1, card1.point, card1.suit)
3.魔術方法,上述的三個成員方法都是魔術方法,在執行某些操作或調用內置函數後,解釋器會自動調用這些方法,魔術方法的函數名兩邊是雙下劃線
inst=cards()
print(len(inst))
print(inst[0], inst[-1], inst[22])
在cards的對象被創建時,會自動調用__init__方法,調用len()求cards的長度時,__len__會被自動調用,在使用下標進行操作時,__getitem__會被自動調用
這些魔術方法並不需要主動調用,在某些操作或者內置函數被調用時,可以自動被調用
使用random中的choice方法可以做隨機選取,可以使用該方法隨機抽牌
inst=cards() print(rd.choice(inst))
因爲實現了__getitem__,所以還可以做切片,循環遍歷
print(inst[5:30:6])
print('-------------')
for card in cards:
print(card)
print('-------------')
for card in reversed(cards):
print(card)
如果沒有實現__contains__函數,那麼in運算也是做遍歷,所以可以對於cards類,可以使用in運算符
card3=card('10','spades')
card4=card('123','45')
print(card3 in inst)
print(card4 in inst)
可見,執行in操作時,調用了很多次__getitem__方法,其中執行結果爲false的語句將inst遍歷了一遍
對紙牌進行排序
suit_val=dict(spades=3,hearts=2,diamonds=1,clubs=0)#生成一個字典,參數名是key,參數值是value
def sortcards(card):
val=cards.points.index(card.point)#檢查字符串中是否含有card.point,如果有,返回card.point的索引,否則拋出異常
return val*len(suit_val)+suit_val[card.suit]#返回每張牌的相對值(點數列表的索引外加花色,從而根據該值進行比較誰大誰小)
for t in sorted(inst, key=sortcards):#按照sortcards的返回值進行從小到大排序
print(t)
可見,已經將撲克進行了排序,沒有找到可以長截屏的軟件。。。。。。
參考:
《流暢的Python》
歡迎大家評論交流,作者水平有限,如有錯誤,歡迎指出