Python namedtuple(命名元組)使用實例

 

Python namedtuple(命名元組)使用實例python

#!/usr/bin/python3

import collections

MyTupleClass = collections.namedtuple('MyTupleClass',['name', 'age', 'job'])
obj = MyTupleClass("Tomsom",12,'Cooker')
print(obj.name)
print(obj.age)
print(obj.job)

執行結果:sql

Tomsom
12
Cooker

namedtuple對象就如它的名字說定義的那樣,你能夠給tuple命名,具體看下面的例子:數據庫

#!/usr/bin/python3

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)

執行結果:fetch

Type of Person: <class '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

  來解釋一下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的元素。其輸出結果以下:spa

  可是在使用namedtyuple的時候要注意其中的名稱不能使用Python的關鍵字,如:class def等;並且也不能有重複的元素名稱,好比:不能有兩個’age age’。若是出現這些狀況,程序會報錯。可是,在實際使用的時候可能沒法避免這種狀況,好比:可能咱們的元素名稱是從數據庫裏讀出來的記錄,這樣很難保 證必定不會出現Python關鍵字。這種狀況下的解決辦法是將namedtuple的重命名模式打開,這樣若是遇到Python關鍵字或者有重複元素名 時,自動進行重命名。sqlite

看下面的代碼:對象

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

其輸出結果爲:blog

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

  咱們使用rename=True的方式打開重命名選項。能夠看到第一個集合中的class被重命名爲 ‘_2' ; 第二個集合中重複的age被重命名爲 ‘_3'這是由於namedtuple在重命名的時候使用了下劃線 _ 加元素所在索引數的方式進行重命名。索引

附兩段官方文檔代碼實例:文檔

1) namedtuple基本用法

>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22) # instantiate with positional or keyword arguments
>>> p[0] + p[1] # indexable like the plain tuple (11, 22)
33
>>> x, y = p # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessible by name
33
>>> p # readable __repr__ with a name=value style
Point(x=11, y=22)

2) namedtuple結合csv和sqlite用法

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
print(emp.name, emp.title)
import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
print(emp.name, emp.title)
相關文章
相關標籤/搜索