流畅的Python第二章

本章主要介绍了Python中tuple和list的一些知识。

列表解析和生成器表达式

使用()可以得到一个生成器,可以看出,生成器的内存使用更少。

>>> a = [i for i in range(10)]
>>> g = (i for i in range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> g
<generator object <genexpr> at 0x107deca50>
>>> a.__sizeof__()
168
>>> g.__sizeof__()
48

Python3中的列表推导没有了变量泄漏问题

python2中:

>>> x = 'my var'
>>> dummy = [x for x in 'ABC']
>>> x
'C'

python3中:

>>> x = 'my var'
>>> dummy = [x for x in 'ABC']
>>> x
'my var'
>>> dummy
['A', 'B', 'C']

使用*处理剩下的元素

>>> a, b , *part, c = range(10)
>>> part
[2, 3, 4, 5, 6, 7, 8]

关于namedtuple

namedtuple Returns a new tuple subclass named typename.

>>> from collections import namedtuple
>>> Point = namedtuple('Point', ['x', 'y'], verbose=True)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class Point(tuple):
    'Point(x, y)'
    __slots__ = ()
    _fields = ('x', 'y')
    def __new__(_cls, x, y):
        'Create new instance of Point(x, y)'
        return _tuple.__new__(_cls, (x, y))
    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Point object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result
    def _replace(_self, **kwds):
        'Return a new Point object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('x', 'y'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % list(kwds))
        return result
    def __repr__(self):
        'Return a nicely formatted representation string'
        return self.__class__.__name__ + '(x=%r, y=%r)' % self
    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values.'
        return OrderedDict(zip(self._fields, self))
    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self)
    x = _property(_itemgetter(0), doc='Alias for field number 0')
    y = _property(_itemgetter(1), doc='Alias for field number 1')

可以看出,Point类继承自tuple类,通过__slots____dict__设置为空,只有两个可读属性x和y。

使用*操作列表

使用 * 复制列表时候,可能是同一个元素的引用。
比如:

>>> a = [[]]*3
>>> a
[[], [], []]
>>> a[0].append(1)
>>> a
[[1], [1], [1]]

一个关于+=的谜题

tuple是不可变的,但是如果tuple里面有可变的元素,比如:

>>> atuple = (1,2,3,[1,2,3,4])
>>> atuple[3] += [5,6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> atuple
(1, 2, 3, [1, 2, 3, 4, 5, 6])

这里会出现异常,但是对tuple的修改也变了。

说明在tuple中最好不要放可以改变的元素。

关于dis模块分析查看字节码

「点点赞赏,手留余香」

    还没有人赞赏,快来当第一个赞赏的人吧!