简单讲解Python编程中namedtuple类的用法

yipeiwu_com5年前Python基础

Python的Collections模块提供了不少好用的数据容器类型,其中一个精品当属namedtuple。

namedtuple能够用来创建类似于元祖的数据类型,除了能够用索引来访问数据,能够迭代,更能够方便的通过属性名来访问数据。

在python中,传统的tuple类似于数组,只能通过下标来访问各个元素,我们还需要注释每个下标代表什么数据。通过使用namedtuple,每个元素有了自己的名字,类似于C语言中的struct,这样数据的意义就可以一目了然了。当然,声明namedtuple是非常简单方便的。
代码示例如下:

from collections import namedtuple
 
Friend=namedtuple("Friend",['name','age','email'])
 
f1=Friend('xiaowang',33,'xiaowang@163.com')
print(f1)
print(f1.age)
print(f1.email)
f2=Friend(name='xiaozhang',email='xiaozhang@sina.com',age=30)
print(f2)
 
name,age,email=f2
print(name,age,email)

类似于tuple,它的属性也是不可变的:

>>> big_yellow.age += 1
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AttributeError: can't set attribute

能够方便的转换成OrderedDict:

>>> big_yellow._asdict()
OrderedDict([('name', 'big_yellow'), ('age', 3), ('type', 'dog')])

方法返回多个值得时候,其实更好的是返回namedtuple的结果,这样程序的逻辑会更加的清晰和好维护:

>>> from collections import namedtuple
>>> def get_name():
...   name = namedtuple("name", ["first", "middle", "last"])
...   return name("John", "You know nothing", "Snow")
...
>>> name = get_name()
>>> print name.first, name.middle, name.last
John You know nothing Snow

相比tuple,dictionary,namedtuple略微有点综合体的意味:直观、使用方便,墙裂建议大家在合适的时候多用用namedtuple。

相关文章

Python3实现的回文数判断及罗马数字转整数算法示例

本文实例讲述了Python3实现的回文数判断及罗马数字转整数算法。分享给大家供大家参考,具体如下: 回文数 判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一...

python smtplib模块自动收发邮件功能(一)

python smtplib模块自动收发邮件功能(一)

自动化测试的脚本运行完成之后,可以生成test report,如果能将result自动的发到邮箱就不用每次打开阅读,而且随着脚本的不段运行,生成的报告会越来越多,找到最近的报告也是一个比...

Python实现CET查分的方法

Python CET自动查询方法需要用到的python方法模块有:sys、urllib2 本文实例讲述了Python实现CET查分的方法。分享给大家供大家参考。具体实现方法如下: 复制代...

python逐行读取文件内容的三种方法

方法一:复制代码 代码如下:f = open("foo.txt")          ...

python正则表达式re之compile函数解析

re正则表达式模块还包括一些有用的操作正则表达式的函数。下面主要介绍compile函数。 定义: compile(pattern[,flags] ) 根据包含正则表达式的字符串创...