1.1 一摞 python 风格的纸牌
【主要代码来自书中,故为转载】
# encoding: utf-8
import collections
# collections.namedtuple 用于构建只有少数属性,且没有方法的对象
print("此处构建一副纸牌")
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]
#been_card = Card('7', 'diamonds')
#print(been_card)
deck = FrenchDeck()
#print("纸牌总数:", str(len(deck)))
print("取出第一张纸牌和最后一张纸牌")
print(deck[0])
print(deck[-1])
# random.chioce 该函数可以从一个序列中随机选出一个元素
from random import choice
print("从扑克牌中随机选出张")
print(choice(deck))
print(choice(deck))
print(choice(deck))
print("查看最上面三张牌")
print(deck[:3])
print("先抽出第12张牌,然后每隔13张取一张")
print(deck[12::13])
# 迭代这副牌
#for card in deck:
# print(card)
print("判断某张牌是否存在")
print(Card('Q', 'hearts') in deck)
print(Card('Q', 'bearts') in deck)
print("排序")
suit_values = dict(spades=3,hearts=2,diamonds=1,clubs=0)
def spades_high(card):
rank_value = FrenchDeck.ranks.index(card.rank)
return rank_value * len(suit_values) + suit_values[card.suit]
# sort() 方法直接改变 序列顺序,而sorted() 方法是创建一个有序的副本
# sort(key = len) 要求按照元素字符串长度升序排序-key知识点
# sort(reverse = True) 要求降序排序-reverse知识点
for card in sorted(deck, key=spades_high):
print(card)