Python总结 八

字典

无论如何都要取到值

dct[key] = dct.get(key, 0) + 1

关于 dct.get(key[, default]) ,如果 key 存在,返回 dct[key],否则返回 default

Counter

如果你在使用Python 2.7,你就可以用Counter来计数了:

>>> from collections import Counter
>>> d = [1, 1, 1, 2, 2, 3, 1, 1]
>>> Counter(d)
Counter({1: 5, 2: 2, 3: 1})

namedtuple()

namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性。这对象更像带有数据属性的类,不过数据属性是只读的。

>>> from collections import namedtuple
>>> TPoint = namedtuple('TPoint', ['x', 'y'])
>>> p = TPoint(x=10, y=10)
>>> p
TPoint(x=10, y=10)
>>> p.x
10
>>> p.y
10
>>> p[0]
10
>>> type(p)
<class '__main__.TPoint'>
>>> for i in p:
    print(i)

全貌

TPoint = namedtuple('TPoint', ['x', 'y'], verbose=True)
from builtins import property as _property, tuple as _tuple
from operator import itemgetter as _itemgetter
from collections import OrderedDict
class TPoint(tuple):
    'TPoint(x, y)'
    __slots__ = ()
    _fields = ('x', 'y')
    def __new__(_cls, x, y):
        'Create new instance of TPoint(x, y)'
        return _tuple.__new__(_cls, (x, y))
    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new TPoint 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 __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))
    __dict__ = property(_asdict)
    def _replace(_self, **kwds):
        'Return a new TPoint 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 __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')

namedtuple最常用还是出现在处理来csv或者数据库返回的数据上。利用map()函数和namedtuple建立类型的_make()方法。

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print(emp.name, emp.title)