• 《流畅的python》:python风格的纸牌


    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')
        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]

    代码说明:

    1、首先用collections.namedtuple构建了一个类来表示纸牌,文档:https://docs.python.org/zh-cn/3/library/collections.html#collections.namedtuple

    这样的类特点:可以通过字段名、索引获取字段值

    2、FrenchDeck类实现了特殊方法__len__,__getitem__,将对象的len(),[]操作转到对cards属性的操作

    3、实现了__getitem__方法,对象将变成可以迭代

    测试代码如下:

       deck = FrenchDeck()
        print(deck)
        print(deck._cards)
        print(len(deck))
        print(choice(deck))
        print(deck[0])
        print(deck[1])
        print(deck[12::13])
    
        # for card in deck:
        #     print(card)
        #
        #反向迭代
        for card in reversed(deck):
            print(card)

    测试结果如下

    对扑克牌进行排序:2最小,A最大;同时加上花色的判定;花色值为0-51

    def spades_high(card):
        suit_values = dict(spades=3,hearts=2,diamonds=1,clubs=0)
        rank_value = FrenchDeck.ranks.index(card.rank)
    
        res = rank_value * len(suit_values) + suit_values[card.suit]
        return res
    
    if __name__ == '__main__':
        deck = FrenchDeck()
        print(sorted(deck,key=spades_high))
  • 相关阅读:
    爬虫基础
    设计BBS
    中间件和auth模块
    git
    分页器与form表单
    cookie与session
    springboot2.x基础教程:@Enable原理
    springboot2.x基础教程:@Scheduled开启定时任务及源码分析
    springboot2.x基础教程:@Async开启异步任务
    springboot2.x基础教程:JRebel实现SpringBoot热部署
  • 原文地址:https://www.cnblogs.com/Xiaojiangzi/p/13862327.html
Copyright © 2020-2023  润新知