Python的collections模塊中namedtuple結構使用示例

分類:IT技術 時間:2016-10-11

namedtuple 就是命名的 tuple,比較像 C 語言中 struct。一般情況下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能按照 index 訪問,沒有明確的稱呼,而 namedtuple 就是事先把這些 item 命名,以後可以方便訪問。

from collections import namedtuple


# 初始化需要兩個參數,第一個是 name,第二個參數是所有 item 名字的列表。
coordinate = namedtuple('Coordinate', ['x', 'y'])

c = coordinate(10, 20)
# or
c = coordinate(x=10, y=20)

c.x == c[0]
c.y == c[1]
x, y = c

namedtuple 還提供了 _make 從 iterable 對象中創建新的實例:

coordinate._make([10,20])

再來舉個栗子:

# -*- coding: utf-8 -*-
"""
比如我們用戶擁有一個這樣的數據結構,每一個對象是擁有三個元素的tuple。
使用namedtuple方法就可以方便的通過tuple來生成可讀性更高也更好用的數據結構。
"""
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
 print website[0], website.url

結果:

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


Tags: Website website import 王誌東 高也

文章來源:


ads
ads

相關文章
ads

相關文章

ad