{{ cat }}'s docs

1.2.0 使tuple易读的几种方法


1. 常规使用tuple的方法

>>> student_info = [("zack", 18, "male", "zack@gmail.com"), ("harry", 38, "male", "harry@gmail.com"), ("tom", 27, "male", "tom@gmail.com")]

>>> for student in student_info:
>>>     if student[1] > 21:
>>>         print "name:%-6s, age:%2d, sex:%-6s, email:%s"\
>>>                 % (student[0], student[1], student[2], student[3])      
name:harry , age:38, sex:male  , email:harry@gmail.com
name:tom   , age:27, sex:male  , email:tom@gmail.com

使用这种方式,索引值无法很直观的表示代码的含义


2. 易用方式1

>>> name, age, sex, email = xrange(4)

>>> for student in student_info:
>>>     if student[1] > 21:
>>>         print "name:%-6s, age:%2d, sex:%-6s, email:%s"\
>>>                 % (student[name], student[age], student[sex], student[email])     
name:harry , age:38, sex:male  , email:harry@gmail.com
name:tom   , age:27, sex:male  , email:tom@gmail.com

将0123这些毫无意义的索引值转换成有意义的变量名称


3. 易用方式2-namedtuple

>>> from collections import namedtuple

>>> Student_info = namedtuple('Student_info', ['name', 'age', 'sex', 'email'])

>>> for student in student_info:
>>>     if student[1] > 21:
>>>         student = Student_info(*student)
>>>         print "name:%-6s, age:%2d, sex:%-6s, email:%s"\
>>>                 % (student.name, student.age, student.sex, student.email)       
name:harry , age:38, sex:male  , email:harry@gmail.com
name:tom   , age:27, sex:male  , email:tom@gmail.com

使用*tuple的方式将tuple的内容传递给新的namedtuple,然后使用student.age的方式调用