18 Jan 2017
>>> student_info = [("opsuser", 18, "male", "opsuser@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
使用这种方式,索引值无法很直观的表示代码的含义
>>> 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这些毫无意义的索引值转换成有意义的变量名称
>>> 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的方式调用