Python的collections模块中namedtuple结构使用示例
2024-10-12 12:28:42
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 = [ ] 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') |
最新文章
- 极路由访问Apple Store可以浏览但是不能下载的解决方案
- VBS实现定时发送邮件
- eclipse中输入中文为繁体
- C# WebService URL重写
- Hadoop 2.2.0 4结点集群安装 非HA
- ajax 异步请求webservice(XML格式)
- SQL多条件查询
- rpc rmi http
- LFS7.4编译笔记(2)
- [AngularJS] Provider
- 【OpenGL】入门
- RabbitMQ 配置文件无法成功应用
- Ubuntu 出现apt-get: Package has no installation candidate问题
- Java中ArrayList类详解
- U-Boot在FL2440上移植(二)----支持NOR Flash
- 团队作业4——第一次项目冲刺(ALpha版本)第四天
- C语言之二维数组棋盘游戏
- Beta冲刺合集
- Struts2之配置文件中Action的详细配置(续)
- 解决 Vue 动态生成 el-checkbox 点击无法赋值问题
热门文章
- nginx -s stop and -s quit 有什么区别?
- 解析XML异常
- VS2015 LINK : fatal error LNK1264: 已指定 /GENPROFILE 但没有所需的代码生成;检测失败
- ZOJ - 3216:Compositions (DP&;矩阵乘法&;快速幂)
- 只需 5 秒钟,你就能取到 WPF 程序的超高分辨率超高清截图
- LG2024 [NOI2001]食物链
- 转 update关联更新在sqlserver和oracle中的实现
- C++和C#转换
- [转]Maven中profile和filtering实现多个环境下的属性过滤
- Angular 4 模板表单校验