python的Collections模塊提供了不少好用的數據容器類型,其中一個精品當屬namedtuple。
namedtuple能夠用來創建類似於元祖的數據類型,除了能夠用索引來訪問數據,能夠叠代,更能夠方便的通過屬性名來訪問數據。
在python中,傳統的tuple類似於數組,只能通過下標來訪問各個元素,我們還需要註釋每個下標代表什麽數據。通過使用namedtuple,每個元素有了自己的名字,類似於C語言中的struct,這樣數據的意義就可以一目了然了。當然,聲明namedtuple是非常簡單方便的。
代碼示例如下:
from collections import namedtuple Friend=namedtuple("Friend",['name','age','email']) f1=Friend('xiaowang',33,'[email protected]') print(f1) print(f1.age) print(f1.email) f2=Friend(name='xiaozhang',email='[email protected]',age=30) print(f2) name,age,email=f2 print(name,age,email)
類似於tuple,它的屬性也是不可變的:
>>> big_yellow.age += 1 Traceback (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.last John You know nothing Snow
相比tuple,dictionary,namedtuple略微有點綜合體的意味:直觀、使用方便,墻裂建議大家在合適的時候多用用namedtuple。
Tags: nothing python recent return import
文章來源: