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在重命名的時候使用了下劃線 _ 加元素所在索引數的方式進行重命名。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章