python  collections中namedtuple()

python模块collections中namedtuple()的理解

原创 2016年09月28日 17:32:30

Python中存储系列数据,比较常见的数据类型有list,除此之外,还有tuple数据类型。相比与list,tuple中的元素不可修改,在映射中可以当键使用。tuple元组的item只能通过index访问,collections模块的namedtuple子类不仅可以使用item的index访问item,还可以通过item的name进行访问。可以将namedtuple理解为c中的struct结构,其首先将各个item命名,然后对每个item赋予数据。

[python] view plain copy
  1. coordinate = namedtuple('Coordinate', ['x''y'])  
  2. co = coordinate(10,20)  
  3. print co.x,co.y  
  4. print co[0],co[1]  
  5. co = coordinate._make([100,200])  
  6. print co.x,co.y  
  7. co = co._replace(x = 30)  
  8. print co.x,co.y  


results:
10 20
10 20
100 200
30 200

[python] view plain copy
  1. from collections import namedtuple  
  2.   
  3. websites = [  
  4.     ('Sohu''http://www.google.com/', u'张朝阳'),  
  5.     ('Sina''http://www.sina.com.cn/', u'王志东'),  
  6.     ('163''http://www.163.com/', u'丁磊')  
  7. ]  
  8.   
  9. Website = namedtuple('Website', ['name''url''founder'])  
  10.   
  11. for website in websites:  
  12.     website = Website._make(website)  
  13.     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')
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值