Python进阶1——一摞纸牌

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》

 

欢迎大家评论交流,作者水平有限,如有错误,欢迎指出

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章