2-2为元组中的元素命名
如何为元组中的每个元素命名,提高程序可读性。例如:

1、实现方法
1.1 给index指定数值常量,类似C里的枚举
利用列表拆包的方式给变量赋值(我们不再改变他的值,使用全大写类似C的宏定义)
>>> NAME,AGE,SEX,EMAIL = xrange(4) >>> NAME 0 >>> AGE 1 >>> SEX 2 >>> EMAIL 3 >>>student =('Bob',20,'male','bob@gmail.com') >>> student ('Bob', 20, 'male', 'bob@gmail.com') >>> student[NAME] 'Bob' >>> student[AGE] 20 >>> student[EMAIL] 'bob@gmail.com'
1.2使用标准库中collections.namedtuple替代内置tuple,自定义一个tuple子类,这种方式开销仅仅比普通元组高一些。
>>> from collections import namedtuple #使用namedtuple,创造出一个'Student'类(tuple元组的子类),并有'name','age','sex','email'的元素(即下标为0,1,2,3) >>>namedtuple('Student',['name','age','sex','email']) <class '__main__.Student'> #可以看出他是一个class >>> stu = namedtuple('Student',['name','age','sex','email']) #将这个类命名为stu >>> s = stu('lucy', 18, 'female', 'lucy@gmail.com')#使用位置参数创建一个stu类的变量s >>> s2 = stu(name ='lily', age=18, sex='female', email='lily@gmail.com')#使用关键字参数创建一个stu类的变量s2 >>> s.name 'lucy' >>> s[0] 'lucy' >>> s2.name 'lily' #可以看出用变量的属性和索引都能获取到元素。 >>> isinstance(s,tuple) True #可以看出变量s是一个元组的子类
2扩展知识
>>> from collections import namedtuple >>> help(namedtuple) Help on function namedtuple in module collections: namedtuple(typename, field_names, verbose=False, rename=False) Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields Point(x=100, y=22)
namedtuple是一个函数,它用来创建一个自定义的tuple对象,并且规定了tuple元素的个数,并可以用属性而不是索引来引用tuple的某个元素。
这样一来,我们用namedtuple可以很方便地定义一种数据类型,它具备tuple的不变性,又可以根据属性来引用,使用十分方便。
如文中例子
posted on 2018-03-16 10:10 石中玉smulngy 阅读(172) 评论(0) 收藏 举报
浙公网安备 33010602011771号