开发环境:以Python2.x为主 IPython
第二天 : 02day
如何为元组中的每个元素命名,提高程序的可读性?
实际案列:学生信息系统中数据为固定格式:
(姓名,年龄,性别,邮箱,地址...)
学生数量很大为了减少存储开销,对每个学生信息用元组表示:
('Jim',18,'male','Jim123@qq.com')
('Lilei',20,'male','liLei456@163.com')
('Hangmeimei',19,'Hangmeimei@163.com')
......
访问时,我们使用引索(index)访问,大量引索降低程序的可读性,如何解决这个问题?
通常我们访问元组的方式如下:
In [38]: student = ('king',18,'male','38277946@qq.com')
In [39]: student[0]
Out[39]: 'king'
In [40]: student[2]
Out[40]: 'male'
In [41]: student[1]
Out[41]: 18
In [42]: student[3]
Out[42]: '38277946@qq.com'
解决方案:
方案1:
定义类似于其它语言的枚举类型,也就是定义一系列的数值常量
In [38]: student = ('king',18,'male','38277946@qq.com')
In [49]: NAME = 0
In [50]: AGE = 1
In [51]: SEX = 2
In [52]: EMAIL = 3
In [53]: student[NAME]
Out[53]: 'king'
In [54]: student[AGE]
Out[54]: 18
In [55]: student[SEX]
Out[55]: 'male'
In [56]: student[EMAIL]
Out[56]: '38277946@qq.com'
简化以上的操作方法:
In [62]: NAME,AGE,SEX,EMAIL = xrange(4)
In [63]: student[NAME]
Out[63]: 'king'
In [64]: student[AGE]
Out[64]: 18
In [65]: student[SEX]
Out[65]: 'male'
In [66]: student[EMAIL]
Out[66]: '38277946@qq.com'
方案2:
使用标准库中collections.namedtuple替代内置tuple
In [67]: from collections import namedtuple
In [68]: Student = namedtuple('Student',['name','age','sex','email'])
In [69]: Student
Out[69]: __main__.Student
In [70]: s = Student('king',18,'male','38277946@qq.com')
In [71]: s.name
Out[71]: 'king'
In [72]: s.age
Out[72]: 18
In [73]: s.sex
Out[73]: 'male'
In [74]: s.email
Out[74]: '38277946@qq.com'
In [75]: isinstance(s,tuple)
Out[75]: True