• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python的collections模块中namedtuple结构使用示例

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

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了python namedtuple,python collections,python中collections,namedtuple,python代码示例等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

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

</div>

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

coordinate._make([10,20])

</div>

再来举个栗子:

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

结果:

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/
</div>

</div>

您可能想查找下面的文章:

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

相关文章

  • python基础教程之实现石头剪刀布游戏示例
  • python创建临时文件夹的方法
  • python获取目录下所有文件的方法
  • django轻松使用富文本编辑器CKEditor的方法
  • Python过滤列表用法实例分析
  • 基于python yield机制的异步操作同步化编程模型
  • 低版本中Python除法运算小技巧
  • 在Python中使用模块的教程
  • Python列出一个文件夹及其子目录的所有文件
  • win7 下搭建sublime的python开发环境的配置方法

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • python脚本实现数据导出excel格式的简单方法(推荐)
    • 详解python 字符串和日期之间转换 StringAndDate
    • Python写的一个定时重跑获取数据库数据
    • 合并Excel工作薄中成绩表的VBA代码,非常适合教育一线的朋友
    • Python多线程编程(二):启动线程的两种方法
    • python使用7z解压apk包的方法
    • 详解Python使用simplejson模块解析JSON的方法
    • Python字符和字符值(ASCII或Unicode码值)转换方法
    • Python Requests安装与简单运用
    • 用ReactJS和Python的Flask框架编写留言板的代码示例

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有