最近在慢慢看几页,
第一章的示例代码,实现一副扑克牌。
确实老辣~
不是高手,没有这感觉,我慢慢学吧。
import collectionsfrom random import choiceCard = collections.namedtuple('Card', ['rank', 'suit'])class FrechDeck: 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]suit_values = dict(spades=3, hearts=2, diamonds=3, clubs=4)def spades_high(card): rank_value = FrechDeck.ranks.index(card.rank) return rank_value * len(suit_values) + suit_values[card.suit]beer_card = Card('7', 'diamonds')print(beer_card)deck = FrechDeck()print(len(deck))print(deck[0])print(deck[-1])print(choice(deck))print(deck[:3])print(deck[12::13])for card in deck: # print(card) passfor card in reversed(deck): # print(card) passprint(Card('Q', 'hearts') in deck)print(Card('7', 'beats') in deck)for card in sorted(deck, key=spades_high): # print(card) pass
输出:
Card(rank='7', suit='diamonds')52Card(rank='2', suit='spades')Card(rank='A', suit='hearts')Card(rank='7', suit='hearts')[Card(rank='2', suit='spades'), Card(rank='3', suit='spades'), Card(rank='4', suit='spades')][Card(rank='A', suit='spades'), Card(rank='A', suit='diamonds'), Card(rank='A', suit='clubs'), Card(rank='A', suit='hearts')]TrueFalseProcess finished with exit code 0