Python简单实现⼀副扑克牌
Python实现数据模型⼀副扑克牌
⼀、⾸先我们写类
import collections
Card = collections.namedtuple('Card',['rank','suit'])
class FrenchDeck:
ranks =[str(n)for n in range(2,11)]+list('JQKA')
suits ='spades diamonds clubs hearts'.split()
def__init__(self):
self._cards =[Card(rank,suit)for rank in self.ranks for suit in self.suits]
def__len__(self):
return len(self._cards)
def__getitem__(self,position):
return self._cards[position]
beer_card = Card('7','diamonds')
print(beer_card)
deck = FrenchDeck()
print(len(deck))
print(deck[0])
可以⽤len()函数来查看⼀副牌有多少张
从⼀副牌中抽取特定的⼀张纸牌,⽐如说第⼀张或最后⼀张,是很容易的:deck[0]或deck[-1],这都是由__getitem__⽅法提供的。
⼆、随机选牌
如果我们需要随机选出三张牌,我们就⽤random.choice就⾏,直接加进去就⾏
deck = FrenchDeck()
from random import choice
for i in range(3):
print(choice(deck))
三、其他操作
因为__getitem__⽅法把【】操作交给了self._cards列表,所以我们的deck类⾃动⽀持切⽚(slicing)操作。下⾯我们列出查看⼀副牌中最上⾯3张和只看牌⾯是A的牌的操作。其中第⼆种操作的具体⽅法是,先抽取索引是12的那张牌,然后每隔13张牌拿1张:
deck = FrenchDeck()
print(deck[:3])
[Card(rank='2', suit='spades'), Card(rank='3', suit='spades'), Card(rank='4', suit='spades')]
deck = FrenchDeck()
print(deck[12::13])
快速排序python实现[Card(rank='A', suit='spades'), Card(rank='A', suit='diamonds'), Card(rank='A', suit='clubs'), Card(rank='A', suit='hearts')]
迭代通常是隐式的,譬如说⼀个集合类型没有实现__contains__⽅法,那么in运算符就会按顺序做⼀次迭代搜素。于是,in运算符可以⽤在我们的FrenchDeck类上,因为它是可迭代的:
deck = FrenchDeck()
print(Card('Q','clubs')in deck) print(Card('7','beasts')in deck)
True
False

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。