collections模块里的:namedtuple
来源:互联网 发布:诺基亚3310软件下载 编辑:程序博客网 时间:2024/05/29 09:58
from collections import namedtuple# 定义一个namedtuple类型User,并包含name,sex和age属性。User = namedtuple('User', ['name', 'sex', 'age'])# 创建一个User对象user = User(name='kongxx', sex='male', age=21)# 也可以通过一个list来创建一个User对象,这里注意需要使用"_make"方法user = User._make(['kongxx', 'male', 21])print user# User(name='user1', sex='male', age=21)# 获取用户的属性print user.nameprint user.sexprint user.age# 修改对象属性,注意要使用"_replace"方法user = user._replace(age=22)print user# User(name='user1', sex='male', age=21)# 将User对象转换成字典,注意要使用"_asdict"print user._asdict()# OrderedDict([('name', 'kongxx'), ('sex', 'male'), ('age', 22)])
Namedtuples对于将字段名称分配给csv或sqlite3模块返回的结果元组特别有用:
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')import csvfor emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))): print(emp.name, emp.title)import sqlite3conn = 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)
详细参考:https://docs.python.org/3/library/collections.html#collections.namedtuple
0 0
- collections模块里的:namedtuple
- python模块collections中namedtuple()的理解
- Python的collections模块及namedtuple详解
- python模块collections中namedtuple()的理解
- Collections -- namedtuple
- 关于Python3的collections.namedtuple和functools.namedtuple的探讨
- 自定义命名的元组collections.namedtuple
- Python的defaultdict模块和namedtuple模块
- Python的defaultdict模块和namedtuple模块
- hackerrank Collections.namedtuple()
- python中collections 模块里的defaultdict()函数
- Python HackerRank|Collections.namedtuple(from collections import namedtuple)
- Python 的 defaultdict 模块和 namedtuple 模块(xianglong.me)
- 命名元组 collections.namedtuple
- python from collections import namedtuple
- python的collections模块
- tensorflow学习——collections.namedtuple函数
- Python:collections模块的用法
- 如何通过Html网页调用本地安卓app?
- TCP状态机
- 找工作有哪些网站?
- vc2012编译speex (编译通过)
- WIN7登陆界面去掉下面"windows 7 旗舰版"
- collections模块里的:namedtuple
- 1006. Sign In and Sign Out (25)
- Struts2标签小结
- [openstack]proxy后devstack方式安装openstack
- Android Gradle多渠道批量打包
- ARToolkit Part 3: Locating Vertices 详解
- MyBatis学习 之 一、MyBatis简介与配置MyBatis+Spring+MySql
- 在O(1)时间删除链表结点
- Python 图片识别