为元组中的每个元素命名,提高程序可读性

为元组中的每个元素命名,提高程序可读性

元组中,使用索引(index)访问时,会出现大量索引,降低程序的可读性。

解决方法:
1: 定义类似与其他语言的枚举类型,也就是定义一系列数值常量

eg_v1:定义一个学生信息的元组,包括姓名,年龄,性别,邮箱
("aaaa",22,"boy","aaaaa@123.com")
("bbbb",20,"boy","bbbbb@123.com")
("cccc",22,"girl","ccccc@123.com")
("dddd",21,"girl","ddddd@123.com")

Name = 0
Age = 1
Sex = 2
Email = 3

或者: Name,Age,Sex,Email = xrange(4)

student = ("aaaa",22,"boy","aaaaa@123.com")
# name
print (student[Name])
# aaaa

# age
print (student[Age])
# 22

# sex
print (student[Sex])
# boy

# email
print (student[Email])
# aaaaa@123.com

  



2: 使用标准库中的collection.namedtuple函数替换内置tuple函数

from collections import namedtuple  # 导入namedtuple包
Student = namedtuple("Student",["name","age","sex","email"])
s = Student("aaaa",22,"boy","aaaaa@123.com") # 位置传参 print (s) # Student(name='eeee', age=25, sex='boy', email='eeeee@123.com') s2 = Student(name="eeee",age=25,sex="boy",email="eeeee@123.com") # # 关键字传参 print (s2) # Student(name='eeee', age=25, sex='boy', email='eeeee@123.com') print (s.name) # aaaa print (s.age) # 22 print (s.sex) # boy print (s.email) # aaaaa@123.com print (isinstance(s,tuple)) # 判断是否为tuple元组的子类 # True

  

  


namedtuple 函数的帮助手册:

>>> help(namedtuple)
Help on function namedtuple in module collections:
namedtuple(typename, field_names, verbose=False, rename=False)
Returns a new subclass of tuple with named fields.

>>> Point = namedtuple('Point', ['x', 'y'])
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain tuple
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
>>>

  

 

posted @ 2017-07-12 00:58  xie仗剑天涯  阅读(252)  评论(0编辑  收藏  举报