簡單講解Python編程中namedtuple類的用法,pythonnamedtuple
Python的Collections模組提供了不少好用的資料容器類型,其中一個精品當屬namedtuple。
namedtuple能夠用來建立類似於元祖的資料類型,除了能夠用索引來訪問資料,能夠迭代,更能夠方便的通過屬性名稱來訪問資料。
在python中,傳統的tuple類似於數組,只能通過下標來訪問各個元素,我們還需要注釋每個下標代表什麼資料。通過使用namedtuple,每個元素有了自己的名字,類似於C語言中的struct,這樣資料的意義就可以一目瞭然了。當然,聲明namedtuple是非常簡單方便的。
程式碼範例如下:
from collections import namedtuple Friend=namedtuple("Friend",['name','age','email']) f1=Friend('xiaowang',33,'xiaowang@163.com')print(f1)print(f1.age)print(f1.email)f2=Friend(name='xiaozhang',email='xiaozhang@sina.com',age=30)print(f2) name,age,email=f2print(name,age,email)
類似於tuple,它的屬性也是不可變的:
>>> big_yellow.age += 1Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: can't set attribute
能夠方便的轉換成OrderedDict:
>>> big_yellow._asdict()OrderedDict([('name', 'big_yellow'), ('age', 3), ('type', 'dog')])
方法返回多個值得時候,其實更好的是返回namedtuple的結果,這樣程式的邏輯會更加的清晰和好維護:
>>> from collections import namedtuple>>> def get_name():... name = namedtuple("name", ["first", "middle", "last"])... return name("John", "You know nothing", "Snow")...>>> name = get_name()>>> print name.first, name.middle, name.lastJohn You know nothing Snow
相比tuple,dictionary,namedtuple略微有點綜合體的意味:直觀、使用方便,牆裂建議大家在合適的時候多用用namedtuple。