Python 奇淫巧技 -- 使用元组代替字典, 同时为元组元素命名, 提高可读性
场景:
一般使用字典定义一个人的姓名, 年龄, 性别, 邮箱等信息是非常方便的, 比如:
student_one = {'name': 'Tom', 'age': 19, 'sex': 'male', 'email': 'tom123@hotmail.com'}
使用元组表示则为:
student_one = ('Tom', 19, 'male', 'tom123@hotmail.com')
使用元组替代字典表示信息的时候, 一方面很难分别元素的含义, 另一方面在取值的时候, 需要通过索引 (index) 来获得, 即:
- student_one[0]
- student_one[1]
- student_one[2]
- student_one[3]
当代码量很多的时候, 很难分辨索引分别代表的值是什么, 因此需要给每个索引命名, 来解决难以分辨的问题:
第一种方案: 给索引取 "别名"
- name = 0
- age = 1
- sex = 2
- email = 3
- # 这样即可通过索引的 "别名" 来取值
升级:
- # 通过组包来完成
- name, age, sex, email = range(4)
第二种方案: 使用标准库中的 collections.namedtuple 来替代内置的 tuple
- from collections import namedtuple
- student = namedtuple('student', ['name','age','sex','email'])
- student_one = student("tom", 16, "male", "tom123@hotmail.com")
- print(student_one)
来源: http://www.jianshu.com/p/1a4c35066582