namedtuple()
参考文章地址:http://www.cnblogs.com/herbert/p/3468294.html
namedtuple是继承自tuple的子类。namedtuple和tuple比,有更多更酷的特性。namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性。这对象更像带有数据属性的类,不过数据属性是只读的。
实例如下:
import collections
Mytuple=collections.namedtuple('Mytuple',['x','y'])
n=Mytuple(1,2)
print n.x
1
print n.y
2
print n
Mytuple(x=1, y=2)
namedtuple
Mytuple = namedtuple('TPoint', ['x', 'y']) 创建一个Mytuple类型,而且带有属性x, y.
来解释一下nametuple的几个参数:
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
example
以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的元素。
其输出结果如下:
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
results
几个重要的方法:
1.把数据变成namedtuple类:
Mytuple = namedtuple('Mytuple', ['x', 'y'])
test= [11, 22]
p = Mytuple ._make(test)
p
Mytuple (x=11, y=22)
2. 根据namedtuple创建的类生成的类示例,其数据是只读的,如果要进行更新需要调用方法_replace.
>>> p
Mytuple(x=11, y=22)
>>> p.x
11
>>> p.y
22
>>> p.y=33 Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
p.y=33
AttributeError: can't set attribute
>>> p._replace(y=33)
Mytuple(x=11, y=33)
>>> p
Mytuple(x=11, y=22)
>>>
3.将数据字典转化成namedtuple类型:注意一下p和dp是两个不同的实例,不要被都叫Mytuple给误导了!
>>> d={'x':44,'y':55}
>>> dp=Mytuple(**d)
>>> dp
Mytuple(x=44, y=55)
>>> p
Mytuple(x=11, y=22)
4.namedtuple最常用还是出现在处理来csv或者数据库返回的数据上。利用map()函数和namedtuple建立类型的_make()方法
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) # sqlite数据库
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) # MySQL 数据库
import mysql
from mysql import connector
from collections import namedtuple
user = 'herbert'
pwd = '######'
host = '127.0.0.1'
db = 'world'
cnx = mysql.connector.connect(user=user, password=pwd, host=host,database=db)
cur.execute("SELECT Name, CountryCode, District, Population FROM CITY where CountryCode = 'CHN' AND Population > 500000")
CityRecord = namedtuple('City', 'Name, Country, Dsitrict, Population')
for city in map(CityRecord._make, cur.fetchall()):
print(city.Name, city.Population)