Bruce Han's Blog

A journey of a thousand miles may not be achievied without accumulation of each single step, just as enormous ocean may not be formed without gathering every brook or steam.

0%

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