UnfinishedPython
Python的collections模块提供了工厂函数nametuple(),在使用tuples类型的数据时,创建更加Pythonic的代码。
Tuple
Tuple是Python的一种数据结构,tuples的主要特点是其不可修改,另一方面,仅可以通过整形index进行索引访问,先看一个简单的例子:
person = ('Milton', 'Banana', 174)type(person)# <type 'tuple'># Item accessingprint(person[0], person[1], person[2])# ('Milton', 'Male', 174)# Immutabilityperson[0] = 'Miguel'""" ----------------Traceback (most recent call last):File "<stdin>", line 1, in <module>TypeError: 'tuple' object does not support item assignment"""
从可读性的角度上来说,上面获取数据的方法可读性较差,需要记住tuples中每个元素所对应的index才可以实现清楚地获取数据。
namedtuple
nametuple可以有效地解决上述的缺点,在tuple基础上增加了names,这样可以使代码可读性更高。
from collections import namedtuplePerson = namedtuple('Person',['name','gender','height'])person = Person('Curry', 'Male', 30)issubclass(person, tuple)print(person)print(person.name, person.gender, person.height)person.name='Green'
NameTuple
from typing import NamedTupleclass Person(NamedTuple):name: strage: intheight: intears: int = 2eyes: int = 2milton = Person(name="Milton",age=25,height=174,eyes=1)print(milton.name)
