test

Using Python collections

collections为Python提供了一些加强版的数据结构,譬如OrderedDict,namedtuple等。

1. namedtuple

Python的tuple无法存储数据的对应关系,而namedtuple通过给tuple元素命名实现了数据之间的对应关系(有没有一种Dict的感觉?)

1
2
3
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(11, y=22)

namedtuple既支持tuple的index访问方式,也支持通过属性访问。

1
2
3
4
>>> p[0] + p[1]
33
>>> p.x + p.y
33