『Collections』namedtuple_具名元组

namedtuple()类

需要两个参数,参数一为nametupe名称,参数二为字段一般为序列(多个字段)

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  

 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  

Website(name='Sohu', url='http://www.google.com/', founder=u'u5f20u671du9633')

Website(name='Sina', url='http://www.sina.com.cn/', founder=u'u738bu5fd7u4e1c')

Website(name='163', url='http://www.163.com/', founder=u'u4e01u78ca')

原文地址:https://www.cnblogs.com/hellcat/p/8566038.html