Python的collections模块中namedtuple结构使用示例

yipeiwu_com5年前Python基础

namedtuple 就是命名的 tuple,比较像 C 语言中 struct。一般情况下的 tuple 是 (item1, item2, item3,...),所有的 item 都只能按照 index 访问,没有明确的称呼,而 namedtuple 就是事先把这些 item 命名,以后可以方便访问。

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 对象中创建新的实例:

coordinate._make([10,20])

再来举个栗子:

# -*- 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

结果:

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

相关文章

在vscode中配置python环境过程解析

在vscode中配置python环境过程解析

1.安装vscode和python3.7(安装路径在:E:\Python\Python37); 2.打开vscode,在左下角点击设置图标选择setting,搜索python path,...

使用python动态生成波形曲线的实现

使用python动态生成波形曲线的实现

效果是这个样子的: 用到的模块: * matplotlib.pyplot * matplotlib.animation.FuncAnimation * numpy 三个圆的半径分...

python实现超市扫码仪计费

python实现超市扫码仪计费

python实现超市扫码仪计费的程序主要是使用超市扫码仪扫商品的条形码,读取商品信息,实现计费功能。主要用到的技术是串口通信,数据库的操作,需要的环境包括:python环境,mysql,...

解决django前后端分离csrf验证的问题

第一种方式ensure_csrf_cookie 这种方方式使用ensure_csrf_cookie 装饰器实现,且前端页面由浏览器发送视图请求,在视图中使用render渲染模板,响应给前...

python微信好友数据分析详解

python微信好友数据分析详解

基于微信开放的个人号接口python库itchat,实现对微信好友的获取,并对省份、性别、微信签名做数据分析。 效果: 直接上代码,建三个空文本文件stopwords.txt,ne...