命名元组与普通的元组一样,有着相同的表现特征,其功能就是可以根据名称引用元组中的项,就像根据索引位置一样,这一功能使我们可以创建数据项的聚集。命名的元组需要引入collections模块,该模块提供了namedtuple()函数用于创建自定义元组:
collections.namedtuple(‘define_tuple_type’,’t_field1 t_field2…’)包含两个字符串类型的参数,第一个是自定义元组的类型名,第二个是自定义元组的各元素的名称,可以用元组名.元素名来访问各元素,代码如下:
import collections
t_name=collections.namedtuple(‘t_type’,’t_field1 t_field2 t_field_3’)
print(t_name)==>_main.t_type(t_name自定义元组的类型是t_type)
t1=t_name(‘ybp’,’xl’,’hello’)
print(t1) ==> t_type(t_field1=’ybp’, t_field2=’xl’, t_field_3=’hello world’)
t1.t_field1 ==> ‘ybp’
t1.t_field2 ==> ‘xl’
t1.t_field3 ==> ‘hello’