import collections from random import choice card = collections.namedtuple(‘Card‘,[‘rank‘,‘suit‘]) #构建一个命名元组 class FrenchDeck: ranks = [str(n) for n in range(2,11)] + list(‘JQKA‘) # 创建所有纸牌数A-K suit = ‘黑桃 方块 梅花 红心‘.split() # 创建不同的纸牌花色 def __init__(self): self._cards = [Card(ranks,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] # 获取特定纸牌 deck = FrenchDeck() # 实例化类 print(len(deck)) # 获取整套牌的数量 52 print(deck[0]) # 获取第一张牌 Card(rank=‘2‘,suit=‘黑桃‘) choice(deck) # 随机选取其中某张牌 Card(rank=‘3‘,suit=‘梅花‘) Card(rank=‘5‘,suit=‘红心‘)