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)

最新文章

  1. gcc -Wall -pedantic -ansi(转载)
  2. bootstrap-图文混排 media
  3. Android学习笔记03-搭建Win8下的Android开发环境
  4. 【贴图】网友 snoopy 用《iHMI43 液晶模块》做的界面给大家看看
  5. java技术用ssh从linux服务器下载数据
  6. PHP学习笔记 - 进阶篇(6)
  7. 【Xamarin挖墙脚系列:Xamarin.IOS的程序的结构】
  8. windows下和linux下 Redis 安装
  9. App_Code
  10. Magento - get Attribute Options of the dropdown type attribute
  11. java 正则表达式抽取
  12. 前端UI
  13. Android开发中的安全
  14. CentOS随笔——克隆虚拟机
  15. vue-electron脚手架
  16. Mysql多实例安装笔记
  17. html5 canvas(基本矩形)
  18. [smarty] 在smarty模板中使用smarty变量初始化 javascript 变量的问题
  19. ubuntu密码正确,却不能登录图形界面
  20. LINQ的查询标准操作汇总

热门文章

  1. python threading 模块来实现多线程
  2. 关于LWIP---UDP
  3. AOJ 2249 Road Construction(Dijkstra+优先队列)
  4. libiconv_百度百科
  5. 基于Platinum库的DMS实现(android)
  6. 全国计算机等级考试二级教程-C语言程序设计_第8章_地址和指针
  7. hdu 5583 Kingdom of Black and White(模拟,技巧)
  8. c++中使用c语言函数
  9. SharePoint 2013设置“以其他用户身份登录”
  10. OC中另外的一个常用技术:通知(Notification)