為元組中的每個元素命名,提高程式可讀性
元組中,使用索引(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) >>>