为元组中的每个元素命名,提高程序可读性
Posted xie仗剑天涯
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为元组中的每个元素命名,提高程序可读性相关的知识,希望对你有一定的参考价值。
为元组中的每个元素命名,提高程序可读性
元组中,使用索引(index)访问时,会出现大量索引,降低程序的可读性。
解决方法:
1: 定义类似与其他语言的枚举类型,也就是定义一系列数值常量
eg_v1:定义一个学生信息的元组,包括姓名,年龄,性别,邮箱 ("aaaa",22,"boy","[email protected]") ("bbbb",20,"boy","[email protected]") ("cccc",22,"girl","[email protected]") ("dddd",21,"girl","[email protected]") Name = 0 Age = 1 Sex = 2 Email = 3 或者: Name,Age,Sex,Email = xrange(4) student = ("aaaa",22,"boy","[email protected]") # name print (student[Name]) # aaaa # age print (student[Age]) # 22 # sex print (student[Sex]) # boy # email print (student[Email]) # [email protected]
2: 使用标准库中的collection.namedtuple函数替换内置tuple函数
from collections import namedtuple # 导入namedtuple包 Student = namedtuple("Student",["name","age","sex","email"])
s = Student("aaaa",22,"boy","[email protected]") # 位置传参 print (s) # Student(name=‘eeee‘, age=25, sex=‘boy‘, email=‘[email protected]‘) s2 = Student(name="eeee",age=25,sex="boy",email="[email protected]") # # 关键字传参 print (s2) # Student(name=‘eeee‘, age=25, sex=‘boy‘, email=‘[email protected]‘) print (s.name) # aaaa print (s.age) # 22 print (s.sex) # boy print (s.email) # [email protected] 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) >>>
以上是关于为元组中的每个元素命名,提高程序可读性的主要内容,如果未能解决你的问题,请参考以下文章