1.纸牌代码实现
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 suit in self.suits for rank in self.ranks] def __len__(self): return len(self._cards) def __getitem__(self, position): return self._cards[position]
得到一个纸牌对象:
beer_card = Card('7', 'diamonds') print(beer_card)
FrenchDeck这个类和任何标准Python集合类型一样,可以用len()来查看一叠牌有多少张
deck = FrenchDeck() print(len(deck))
还能通过__getitem__方法抽取特定的牌
print(deck[0], deck[-1])
随机抽牌
from random import choice print(choice(deck)) print(choice(deck)) print(choice(deck))
deck类还支持切片
print(deck[:3]) print(deck[12:13])
这一摞牌还是可迭代的
for card in deck: print(card)