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

yipeiwu_com6年前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。

相关文章

Python找出文件中使用率最高的汉字实例详解

本文实例讲述了Python找出文件中使用率最高的汉字的方法。分享给大家供大家参考。具体分析如下: 这是我初学Python时写的,为了简便,我并没在排序完后再去掉非中文字符,稍微会影响性能...

Python中使用装饰器和元编程实现结构体类实例

Ruby中有一个很方便的Struct类,用来实现结构体。这样就不用费力的去定义一个完整的类来仅仅用作访问属性。 复制代码 代码如下: class Dog < Struct.new(...

Python学习笔记之常用函数及说明

基本定制型 复制代码 代码如下:C.__init__(self[, arg1, ...]) 构造器(带一些可选的参数)C.__new__(self[, arg1, ...]) 构造器(带...

python创建临时文件夹的方法

本文实例讲述了python创建临时文件夹的方法。分享给大家供大家参考。具体实现方法如下: import tempfile, os tempfd, tempname = tempfi...

python 处理数字,把大于上限的数字置零实现方法

如下所示: # coding=utf-8 # 用来处理数字,大于上限的数字置零 f = open("/home/chuwei/桌面/trainA/loss/d_losses.tx...