namedtuple顾名思义,就是名字+元组的数据结构,下面就来看一下Python的collections模块中namedtuple结构使用示例
namedtuple 就是命名的 tuple,比较像 C 语言中 struct。一般情况下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能按照 index 访问,没有明确的称呼,而 namedtuple 就是事先把这些 item 命名,以后可以方便访问。
1
2
3
4
5
6
7
8
9
10
11
12
13
from collections import namedtuple
 
 
# 初始化需要两个参数,第一个是 name,第二个参数是所有 item 名字的列表。
coordinate = namedtuple('Coordinate', ['x', 'y'])
 
c = coordinate(10, 20)
# or
c = coordinate(x=10, y=20)
 
c.x == c[0]
c.y == c[1]
x, y = c

namedtuple 还提供了 _make 从 iterable 对象中创建新的实例:

1
coordinate._make([10,20])

再来举个栗子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# -*- coding: utf-8 -*-
"""
比如我们用户拥有一个这样的数据结构,每一个对象是拥有三个元素的tuple。
使用namedtuple方法就可以方便的通过tuple来生成可读性更高也更好用的数据结构。
"""
from collections import namedtuple
websites = [
 ('Sohu', 'http://www.google.com/', u'张朝阳'),
 ('Sina', 'http://www.sina.com.cn/', u'王志东'),
 ('163', 'http://www.163.com/', u'丁磊')
]
Website = namedtuple('Website', ['name', 'url', 'founder'])
for website in websites:
 website = Website._make(website)
 print website
 print website[0], website.url

结果:

1
2
3
4
5
6
Website(name='Sohu', url='http://www.google.com/', founder=u'\u5f20\u671d\u9633')
Website(name='Sina', url='http://www.sina.com.cn/', founder=u'\u738b\u5fd7\u4e1c')
Website(name='163', url='http://www.163.com/', founder=u'\u4e01\u78ca')

最新文章

  1. 极路由访问Apple Store可以浏览但是不能下载的解决方案
  2. VBS实现定时发送邮件
  3. eclipse中输入中文为繁体
  4. C# WebService URL重写
  5. Hadoop 2.2.0 4结点集群安装 非HA
  6. ajax 异步请求webservice(XML格式)
  7. SQL多条件查询
  8. rpc rmi http
  9. LFS7.4编译笔记(2)
  10. [AngularJS] Provider
  11. 【OpenGL】入门
  12. RabbitMQ 配置文件无法成功应用
  13. Ubuntu 出现apt-get: Package has no installation candidate问题
  14. Java中ArrayList类详解
  15. U-Boot在FL2440上移植(二)----支持NOR Flash
  16. 团队作业4——第一次项目冲刺(ALpha版本)第四天
  17. C语言之二维数组棋盘游戏
  18. Beta冲刺合集
  19. Struts2之配置文件中Action的详细配置(续)
  20. 解决 Vue 动态生成 el-checkbox 点击无法赋值问题

热门文章

  1. nginx -s stop and -s quit 有什么区别?
  2. 解析XML异常
  3. VS2015 LINK : fatal error LNK1264: 已指定 /GENPROFILE 但没有所需的代码生成;检测失败
  4. ZOJ - 3216:Compositions (DP&矩阵乘法&快速幂)
  5. 只需 5 秒钟,你就能取到 WPF 程序的超高分辨率超高清截图
  6. LG2024 [NOI2001]食物链
  7. 转 update关联更新在sqlserver和oracle中的实现
  8. C++和C#转换
  9. [转]Maven中profile和filtering实现多个环境下的属性过滤
  10. Angular 4 模板表单校验