Python namedtuple

我们都知道Python中的tuple是一个非常高效的集合对象,但是我们只能通过索引的方式访问这个集合中的元素,比如下面的代码:

1 Bob=(‘bob‘,30,‘male‘)
2 print‘Representation:‘,Bob
3
4 Jane=(‘Jane‘,29,‘female‘)
5 print‘Field by index:‘,Jane[0]
6
7 for people in[Bob,Jane]:
8     print"%s is %d years old %s" % people

其中Jane[0]就是通过索引访问的一种方式。但是如果tuple中的元素很多的时候操作起来就比较麻烦,有可能会由于索引错误导致出错。我们今天介绍的namedtuple对象就如它的名字说定义的那样,你可以给tuple命名,具体用户看下面的例子:

 1 import collections
 2
 3 Person=collections.namedtuple(‘P‘,‘name age gender‘)
 4 print‘Type of Person:‘,type(Person)
 5
 6 Bob=Person(name=‘B‘,age=30,gender=‘male‘)
 7 print‘Representation:‘,Bob
 8
 9 Jane=Person(name=‘J‘,age=29,gender=‘female‘)
10 print ‘Field by Name:‘,Jane.name
11
12 for people in[Bob,Jane]:
13     print"%s is %d years old %s" % people 

来解释一下nametuple的几个参数,以Person=collections.namedtuple(‘P’,‘name age gender’)为例,其中’Person’是这个namedtuple的名称,后面的’name age gender’这个字符串中三个用空格隔开的字符告诉我们,我们的这个namedtuple有三个元素,分别名为name,age和gender。我们在创建它的时候可以通过Bob=Person(name=’Bob’,age=30,gender=’male’)这种方式,这类似于Python中类对象的使用。而且,我们也可以像访问类对象的属性那样使用Jane.name这种方式访问namedtuple的元素。其输出结果如下:

1 Type of Person: <type ‘type‘>
2 Representation: P(name=‘B‘, age=30, gender=‘male‘)
3 Field by Name: J
4 B is 30 years old male
5 J is 29 years old female

但是在使用namedtyuple的时候要注意其中的名称不能使用Python的关键字,如:class def等;而且也不能有重复的元素名称,比如:不能有两个’age age’。如果出现这些情况,程序会报错。但是,在实际使用的时候可能无法避免这种情况,比如:可能我们的元素名称是从数据库里读出来的记录,这样很难保证一定不会出现Python关键字。这种情况下的解决办法是将namedtuple的重命名模式打开,这样如果遇到Python关键字或者有重复元素名时,自动进行重命名。看下面的代码:

1 import collections
2
3 with_class=collections.namedtuple(‘Person‘,‘name age class gender‘,rename=True)
4 print with_class._fields
5
6 two_ages=collections.namedtuple(‘Person‘,‘name age gender age‘,rename=True)
7 print two_ages._fields 

其输出结果为:

1 (‘name‘, ‘age‘, ‘_2‘, ‘gender‘)
2 (‘name‘, ‘age‘, ‘gender‘, ‘_3‘)

我们使用rename=True的方式打开重命名选项。可以看到第一个集合中的class被重命名为 ‘_2′ ; 第二个集合中重复的age被重命名为 ‘_3′这是因为namedtuple在重命名的时候使用了下划线 _ 加 元素所在索引数的方式进行重命名。

时间: 2025-01-06 07:36:23

Python namedtuple的相关文章

python namedtuple(命名元组)

collections模块基本介绍 collections在通用的容器dict,list,set和tuple之上提供了几个可选的数据类型 namedtuple() factory function for creating tuple subclasses with named fields deque list-like container with fast appends and pops on either end ChainMap dict-like class for creatin

Python namedtuple(命名元组)使用实例

#!/usr/bin/python3 import collections MyTupleClass = collections.namedtuple('MyTupleClass',['name', 'age', 'job']) obj = MyTupleClass("Tomsom",12,'Cooker') print(obj.name) print(obj.age) print(obj.job) 执行结果: Tomsom 12 Cooker namedtuple对象就如它的名字说定

python namedtuple命名元组

from collections import namedtuple Animal=namedtuple('Animal','name age type') perry=Animal(name='perry',age=1,type='cat') print(perry.type) print(perry[0]) print(perry._asdict()) 原文地址:https://www.cnblogs.com/mahailuo/p/10201648.html

python中namedtuple介绍

namedtuple:namedtuple类位于collections模块,有了namedtuple后通过属性访问数据能够让我们的代码更加的直观更好维护.namedtuple能够用来创建类似于元祖的数据类型,除了能够用索引来访问数据,能够迭代,还能够方便的通过属性名来访问数据. 在python中,传统的tuple类似于数组,只能通过下表来访问各个元素,我们还需要注释每个下表代表什么数据.通过使用namedtuple,每哥元素有了自己的名字.类似于C语言中的struct,这样数据的意义就可以一目了

Python之namedtuple源码分析

namedtuple()函数根据提供的参数创建一个新类,这个类会有一个类名,一些字段名和一个可选的用于定义类行为的关键字,具体实现如下 namedtuple函数源码 from keyword import iskeyword as _iskeyword import sys as _sys import logging logging.basicConfig(level=logging.INFO, filename="logging.txt", filemode="w+&qu

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

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

python 命名元组(namedtuple)

我们知道c/c++语言中,有结构体这种数据类型: struct{ string name; int age; char sex; }student; 在对结构体对象进行赋值或者取值时可以使用.运算符进行操作. 那么问题来,python中有没有这个数据类型呢?答案是肯定有的,它就是命名元组(namedtyple). 首先来看一下python中普通元组的不方便之处: Bob=("bob",30,'male') #如果想知道Bobde 名字,则需要使用索引位置进行读取,如下 name=Bob

namedtuple工厂函数,创造一个像实例对象的元祖(感觉到了Python的奇妙与可爱之处)。

发现了namedtuple将大大的方便对象实例化的过程,底层我觉的应该应用了描述符的相关指令__set__,__get__,__delete__等等,深的不讲了,我给自己记号一下如何把这个函数用好. 基本概念 namedtuple是一个 工厂函数,定义在python标准库的collections模块中,使用此函数可以创建一个可读性更强的元组 namedtuple函数所创建(返回)的是一个 元组的子类(python中基本数据类型都是类,且可以在buildins模块中找到) namedtuple函数

python的collection系列-可命名元组(namedtuple)

1 import collections 2 #创建类 3 MytupleClass = collections.namedtuple("MytupleClass",["x","y","z"]) 4 obj = MytupleClass(11,22,33) 5 print(obj.x) 6 print(obj.y) 7 print(obj.z) #应用于坐标 8 #print(help(MytupleClass)) #查看创建