collections

来源:互联网 发布:淘宝童装拍照技巧 编辑:程序博客网 时间:2024/05/17 02:49

namedtuple

collections.namedtuple(typename, field_names[, verbose=False][, rename=False])
Returns a new tuple subclass named typename. The new subclass is used to create tuple-like objects that have fields accessible by attribute lookup as well as being indexable and iterable. Instances of the subclass also have a helpful docstring (with typename and field_names) and a helpful repr() method which lists the tuple contents in a name=value format.

The field_names are a sequence of strings such as [‘x’, ‘y’]. Alternatively, field_names can be a single string with each fieldname separated by whitespace and/or commas, for example ‘x y’ or ‘x, y’.

Any valid Python identifier may be used for a fieldname except for names starting with an underscore. Valid identifiers consist of letters, digits, and underscores but do not start with a digit or underscore and cannot be a keyword such as class, for, return, global, pass, print, or raise.

If rename is true, invalid fieldnames are automatically replaced with positional names. For example, [‘abc’, ‘def’, ‘ghi’, ‘abc’] is converted to [‘abc’, ‘_1’, ‘ghi’, ‘_3’], eliminating the keyword def and the duplicate fieldname abc.

If verbose is true, the class definition is printed just before being built.

Named tuple instances do not have per-instance dictionaries, so they are lightweight and require no more memory than regular tuples.

看了很久才发现这个和C语言的结构体非常的相似。typename是一个新类的的名字,相当于C语言结构体的名字,field_names 是一个字符串序列,相当于C语言中结构体中变量的名字。可以对比一下

Point = namedtuple('_Point', ['x', 'y'])pp = Point(10,1)print(pp)Out: _Point(x=10, y=1)

可以看到输出的类型是_Point而不是Point
对比C语言则是

typedef struct Point{    int x;    int y;}Point

namedtuple还有一些函数也很方便_make可以将可迭代的类型或序列转化为namedtuple,将值与变量名对应起来,非常方便

t = [11, 22]Point._make(t)Out: Point(x=11, y=22)

我们也可以读取一个CSV文件,每一行的数据都与属性名对应起来,操作非常方便(不如Pandas)。

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

可以将字典转化为namedtuple

d = {'x': 11, 'y': 22}Point(**d)Out: Point(x=11, y=22)

这里字典的键必须和field_names 一致。


不可不知的Python模块: collections

原创粉丝点击