python命名元组
利用 collections 模块中的 namedtuple 函数
from collections import namedtuple
namedtuple(typename, field_names)
typename:命名元组的名称;
field_names: 元祖中元素的名称此字段有多种表达方式
三种命名元组定义方式
Student = namedtuple("Student",'id name age sex love')
Student = namedtuple("Student",'id,name,age,sex,love')
Student = namedtuple("Student",['id','name','age','sex','love'])
访问元祖对象中的元素时可以使用逗号操作符(.)读取对象中的元素
s = Student(*(data.split()))
print(s.id)
完整示例
from collections import namedtuple
Student = namedtuple("Student",'id name age sex love')
data = "1 fy 18 male football"
#['1', 'fy', '18', 'male', 'football']
print(data.split())
#1 fy 18 male football
print(*(data.split()))
#Student(id='1', name='fy', age='18', sex='male', love='football')
# 解引用后传递给创建元组的调用,而不用解析每一个字段并为每一个字段进行赋值
print(Student(*(data.split())))
#访问元祖对象中的元素时可以使用逗号操作符(.)读取对象中的元素,而不必像原始元组中,需要记录下标s[2]代表的元素含义
s = Student(*(data.split()))
print(s.id)
print(s.name)
print(s.age)
print(s.sex)
print(s.love)