python namedtuple用法_Python的collections模块中namedtuple结构使用示例
namedtuple 就是命名的 tuple,比較像 C 語言中 struct。一般情況下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能按照 index 訪問,沒有明確的稱呼,而 namedtuple 就是事先把這些 item 命名,以后可以方便訪問。
from collections import namedtuple
# 初始化需要兩個參數(shù),第一個是 name,第二個參數(shù)是所有 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 對象中創(chuàng)建新的實例:
coordinate._make([10,20])
再來舉個栗子:
# -*- coding: utf-8 -*-
"""
比如我們用戶擁有一個這樣的數(shù)據(jù)結(jié)構(gòu),每一個對象是擁有三個元素的tuple。
使用namedtuple方法就可以方便的通過tuple來生成可讀性更高也更好用的數(shù)據(jù)結(jié)構(gòu)。
"""
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
結(jié)果:
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/
總結(jié)
以上是生活随笔為你收集整理的python namedtuple用法_Python的collections模块中namedtuple结构使用示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 什么都愿意是哪首歌啊?
- 下一篇: 亏赚?????????
