如何为元组中的每个元素命名,提高程序可读性?
stuents = ('Jim', 16, 'male', 'jim8721@qq.com')
name=s[0]
age=s[1]
sex= s[2]
email=s[3]
print(name, age, sex, email)
方法一:定义类似与其他语言的枚举类型,也就是定义一系列数值常量
stuents = ('Jim', 16, 'male', 'jim8721@qq.com')
NAME, AGE, SEX, EMAIL = RANGE(3)
name=s[NAME]
age=s[AGE]
sex= s[SEX]
email=s[EMAIL]
print(name, age, sex, email)
方法二:使用标准库中 collections.nameedtuple 替代内置 tuple
In [34]: from collections import namedtuple
In [35]: Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
In [36]: s = Student('Jim', 16, 'male', 'jim182@qq.com')
In [37]: s
Out[37]: Student(name='Jim', age=16, sex='male', email='jim182@qq.com')
In [38]: s.name
Out[38]: 'Jim'
In [39]: s.age
Out[39]: 16
In [40]: s.sex
Out[40]: 'male'
In [41]: s.email
Out[41]: 'jim182@qq.com'