欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

簡(jiǎn)單講解Python編程中namedtuple類的用法

 更新時(shí)間:2016年06月21日 15:36:13   作者:TypingQuietly  
namedtuple類位域Collections模塊中,有了namedtuple后通過(guò)屬性訪問(wèn)數(shù)據(jù)能夠讓我們的代碼更加的直觀更好維護(hù),下面就來(lái)簡(jiǎn)單講解Python編程中namedtuple類的用法

Python的Collections模塊提供了不少好用的數(shù)據(jù)容器類型,其中一個(gè)精品當(dāng)屬namedtuple。

namedtuple能夠用來(lái)創(chuàng)建類似于元祖的數(shù)據(jù)類型,除了能夠用索引來(lái)訪問(wèn)數(shù)據(jù),能夠迭代,更能夠方便的通過(guò)屬性名來(lái)訪問(wèn)數(shù)據(jù)。

在python中,傳統(tǒng)的tuple類似于數(shù)組,只能通過(guò)下標(biāo)來(lái)訪問(wèn)各個(gè)元素,我們還需要注釋每個(gè)下標(biāo)代表什么數(shù)據(jù)。通過(guò)使用namedtuple,每個(gè)元素有了自己的名字,類似于C語(yǔ)言中的struct,這樣數(shù)據(jù)的意義就可以一目了然了。當(dāng)然,聲明namedtuple是非常簡(jiǎn)單方便的。
代碼示例如下:

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=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

能夠方便的轉(zhuǎn)換成OrderedDict:

>>> big_yellow._asdict()
OrderedDict([('name', 'big_yellow'), ('age', 3), ('type', 'dog')])

方法返回多個(gè)值得時(shí)候,其實(shí)更好的是返回namedtuple的結(jié)果,這樣程序的邏輯會(huì)更加的清晰和好維護(hù):

>>> 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略微有點(diǎn)綜合體的意味:直觀、使用方便,墻裂建議大家在合適的時(shí)候多用用namedtuple。

相關(guān)文章

最新評(píng)論