Python namedtuple 具名元组

Python中的tuple是一个非常高效的集合对象,但是我们只能通过索引的方式访问这个集合中的元素,比如下面的

代码:

Bob=('bob',30,'male')  
print 'Representation:',Bob  

Jane=('Jane',29,'female')  
print 'Field by index:',Jane[0]  

for people in [Bob,Jane]:  
    print "%s is %d years old %s" % people  

其中Jane[0]就是通过索引访问的一种方式。

但是,如果tuple中的元素很多的时候,我们操作起来就会比较麻烦,有可能会由于索引错误导致出错。

namedtuple对象就如它的名字所定义的那样,我们可以给tuple命名,具体用法看下面的例子:

import collections  
Person = collections.namedtuple('Person','name age gender')  
print 'Type of Person:', type(Person)  
Bob = Person(name='Bob', age=30, gender='male')  
print 'Representation:', Bob  
Jane = Person(name='Jane', age=29, gender='female')  
print 'Field by Name:', Jane.name  
for people in [Bob,Jane]:  
     print "%s is %d years old %s" % people  
Type of Person: <type 'type'>  
Representation: Person(name='Bob', age=30, gender='male')  
Field by Name: Jane  
Bob is 30 years old male  
Jane is 29 years old female  

看下面的代码:

import collections
with_class=collections.namedtuple('Person','name age class gender',rename=True)
print with_class._fields
two_ages=collections.namedtuple('Person','name age gender age',rename=True)

​ print two_ages._fields其输出结果为:

('name', 'age', '_2', 'gender')
('name', 'age', 'gender', '_3')

我们使用rename=True的方式打开重命名选项。

可以看到第一个集合中的class被重命名为 ‘2′ ; 第二个集合中重复的age被重命名为 ‘3′

这是因为namedtuple在重命名的时候使用了下划线 _ 加元素所在索引数的方式进行重命名。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值