python编程中条件句_简单讲解Python编程中namedtuple类的用法
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=f2
print(name,age,email)
類似于tuple,它的屬性也是不可變的:
>>> big_yellow.age += 1
Traceback (most recent call last):
File "", line 1, in
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。
總結
以上是生活随笔為你收集整理的python编程中条件句_简单讲解Python编程中namedtuple类的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 升级鸿蒙系统有没有翻车,被寄予厚望的华为
- 下一篇: Php中跳转语句goto,phpgoto
