Python namedtuple

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

[python]  view plain copy
  1. Bob=('bob',30,'male')  
  2. print 'Representation:',Bob  
  3. Jane=('Jane',29,'female')  
  4. print 'Field by index:',Jane[0]  
  5. for people in [Bob,Jane]:  
  6.     print "%s is %d years old %s" % people  

    其中Jane[0]就是通过索引访问的一种方式。
    但是如果tuple中的元素很多的时候操作起来就比较麻烦,有可能会由于索引错误导致出错。

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

[python]  view plain copy
  1. import collections  
  2. Person = collections.namedtuple('Person','name age gender')  
  3. print 'Type of Person:', type(Person)  
  4. Bob = Person(name='Bob', age=30, gender='male')  
  5. print 'Representation:', Bob  
  6. Jane = Person(name='Jane', age=29, gender='female')  
  7. print 'Field by Name:', Jane.name  
  8. for people in [Bob,Jane]:  
  9.      print "%s is %d years old %s" % people  

   来解释一下nametuple的几个参数:
        以Person = collections.namedtuple(‘Person’, 'name age gender’)为例,
        其中’Person’是这个namedtuple的名称,后面的’name age gender’这个字符串中三个用空格隔开的字符告诉我们,
        我们的这个namedtuple有三个元素,分别名为name, age和gender。
    我们在创建它的时候可以通过Bob = Person(name=’Bob’, age=30, gender=’male’)这种方式,这类似于Python中类对象的使用。
    而且,我们也可以像访问类对象的属性那样使用Jane.name这种方式访问namedtuple的元素。
    其输出结果如下:
[python]  view plain copy
  1. Type of Person: <type 'type'>  
  2. Representation: Person(name='Bob', age=30, gender='male')  
  3. Field by Name: Jane  
  4. Bob is 30 years old male  
  5. Jane is 29 years old female  

    但是在使用namedtyuple的时候要注意其中的名称不能使用Python的关键字,如:class def等;
    而且也不能有重复的元素名称,比如:不能有两个’age age’。如果出现这些情况,程序会报错。
    但是,在实际使用的时候可能无法避免这种情况,
    比如:可能我们的元素名称是从数据库里读出来的记录,这样很难保 证一定不会出现Python关键字。
    这种情况下的解决办法是将namedtuple的重命名模式打开,这样如果遇到Python关键字或者有重复元素名时,自动进行重命名。

    看下面的代码:
    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、付费专栏及课程。

余额充值