簡單講解Python編程中namedtuple類的用法,pythonnamedtuple

來源:互聯網
上載者:User

簡單講解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。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.