当前位置 > it书童 > 流畅的 python > 正文

第1章 python数据模型

流畅的 python it书童 2019-10-04 15:15:03 0赞 0踩 177阅读 0评论

用python模拟一副扑克牌

import collections

Card = collections.namedtuple('Card', ['rank', 'suit'])


class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA') # 扑克牌点数
    suits = '黑桃 方块 梅花 红桃'.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]
In [1]: from card import *

In [2]: deck = FrenchDeck()

In [3]: len(deck)
Out[3]: 52

In [4]: deck[0]
Out[4]: Card(rank='2', suit='黑桃')

In [5]: deck[-1]
Out[5]: Card(rank='A', suit='红桃')

切片

In [6]: deck[:3]
Out[6]:
[Card(rank='2', suit='黑桃'),
 Card(rank='3', suit='黑桃'),
 Card(rank='4', suit='黑桃')]

In [7]: deck[12::13] # 从第12张开始,每隔13张取一张
Out[7]:
[Card(rank='A', suit='黑桃'),
 Card(rank='A', suit='方块'),
 Card(rank='A', suit='梅花'),
 Card(rank='A', suit='红桃')]

由于deck实现了 __getitem__,因此是可迭代的

In [8]: for card in deck:
   ...:     print(card)
   ...:
Card(rank='2', suit='黑桃')
Card(rank='3', suit='黑桃')
Card(rank='4', suit='黑桃')
Card(rank='5', suit='黑桃')
Card(rank='6', suit='黑桃')
Card(rank='7', suit='黑桃')
...

反向迭代:

In [9]: for card in reversed(deck):
   ...:     print(card)
   ...:
   ...:
Card(rank='A', suit='红桃')
Card(rank='K', suit='红桃')
Card(rank='Q', suit='红桃')
Card(rank='J', suit='红桃')
Card(rank='10', suit='红桃')
...

随机取值

In [10]: from random import choice

In [11]: choice(deck)
Out[11]: Card(rank='3', suit='黑桃')

In [12]: choice(deck)
Out[12]: Card(rank='3', suit='梅花')

根据花式与点数进行排序:

card.py 中新增:

deck = FrenchDeck()

suit_values = dict(黑桃=3, 红桃=2, 方块=1, 梅花=0) # 指定花式的大小

# 对牌进行升序
def spades_high(card):
    rank_value = FrenchDeck.ranks.index(card.rank)
    return rank_value * len(suit_values) + suit_values[card.suit]

重新进入 ipython

In [1]: from card import *

In [2]: deck = FrenchDeck()

In [3]: for card in sorted(deck, key=spades_high):
   ...:     print(card)
   ...:
Card(rank='2', suit='梅花')
Card(rank='2', suit='方块')
Card(rank='2', suit='红桃')
Card(rank='2', suit='黑桃')
Card(rank='3', suit='梅花')
Card(rank='3', suit='方块')

模拟数值类型

from math import hypot

class Vector:

    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __repr__(self):
        # 将对象用字符串的形式表达出来
        return 'Vector(%r, %r)' % (self.x, self.y)

    def __abs__(self):
        return hypot(self.x, self.y)

    def __bool__(self):
        return bool(abs(self))

    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Vector(x, y)

    def __mul__(self, scalar):
        return Vector(self.x * scalar, self.y * scalar)
In [3]: from vector import *

In [4]: v1 = Vector(2, 4)

In [5]: v2 = Vector(2, 1)

In [6]: v1 + v2
Out[6]: Vector(4, 5)

In [7]: v = Vector(3, 4)

In [8]: abs(v)
Out[8]: 5.0

In [9]: v * 3
Out[9]: Vector(9, 12)

In [10]: abs(v * 3)
Out[10]: 15.0
转载须注明出处:https://www.itshutong.com/articles/131/chapter-1-python-data-model
关于我
一个文科出身的程序员,追求做个有趣的人,传播有价值的知识,微信公众号主要分享读书思考心得,不会有代码类文章,非程序员的同学请放心订阅
相关推荐
发表评论
我有句话,不知当讲不当讲?
要讲之前请先 登录