python模塊collections中namedtuple()的理解

Python中存儲系列數據,比較常見的數據類型有list,除此之外,還有tuple數據類型。相比與list,tuple中的元素不可修改,在映射中可以當鍵使用。tuple元組的item只能通過index訪問,collections模塊的namedtuple子類不僅可以使用item的index訪問item,還可以通過item的name進行訪問。可以將namedtuple理解爲c中的struct結構,其首先將各個item命名,然後對每個item賦予數據。

coordinate = namedtuple('Coordinate', ['x', 'y'])
co = coordinate(10,20)
print co.x,co.y
print co[0],co[1]
co = coordinate._make([100,200])
print co.x,co.y
co = co._replace(x = 30)
print co.x,co.y


results:
10 20
10 20
100 200
30 200

from collections import namedtuple

websites = [
    ('Sohu', 'http://www.google.com/', u'張朝陽'),
    ('Sina', 'http://www.sina.com.cn/', u'王志東'),
    ('163', 'http://www.163.com/', u'丁磊')
]

Website = namedtuple('Website', ['name', 'url', 'founder'])

for website in websites:
    website = Website._make(website)
    print website


results:

Website(name='Sohu', url='http://www.google.com/', founder=u'\u5f20\u671d\u9633')
Website(name='Sina', url='http://www.sina.com.cn/', founder=u'\u738b\u5fd7\u4e1c')
Website(name='163', url='http://www.163.com/', founder=u'\u4e01\u78ca')

參考資料:

[1] http://blog.csdn.net/kongxx/article/details/51553362

[2] http://www.jb51.net/article/88144.htm

[3] http://www.jb51.net/article/48771.htm

發佈了76 篇原創文章 · 獲贊 226 · 訪問量 88萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章