学生信息系统:
(名字,年龄,性别,邮箱地址)
为了减少存储开支,每个学生的信息都以一个元组形式存放
如:
('tom', 18,'male','tom@qq.com' )
('jom', 18,'mal','jom@qq.com' ) .......
这种方式存放,如何访问呢?
普通方法:
#!/usr/bin/python3
student = ('tom', 18, 'male', 'tom @ qq.com' )
print(student[0])
if student[1] > 12:
...
if student[2] == 'male':
...
出现问题,程序中存在大量的数字index,可阅读性太差,无法知道每个数字代替的含义
如何解决这个问题?
方法1:
#!/usr/bin/python3
# 给数字带上含义,和元组中一一对应
name, age, sex, email = 0, 1, 2, 3
# 高级:name, age, sex, email = range(4)
student = ('tom', 18, 'male', 'tom @ qq.com' )
print(student[name])
if student[age] > 12:
print('True')
if student[sex] == 'male':
print('True')
这样就直白多了,看名字就知道取什么元素
方法2:
通过 collections库的 nametuple模块
#!/usr/bin/python3
from collections import namedtuple
# 生成一个Student类
Student = namedtuple('Student', ['name', 'age', 'sex', 'email'])
# 生成一条信息对象
s = Student('tom', 18, 'male', 'tom@qq.com')
# 通过类对象进行取数据
print(s.name, s.age, s.sex, s.email)