python 命名元组(namedtuple)
来源:互联网 发布:水仙花c语言 编辑:程序博客网 时间:2024/06/06 15:41
我们知道c/c++语言中,有结构体这种数据类型:
struct{ string name; int age; char sex; }student;
在对结构体对象进行赋值或者取值时可以使用.运算符进行操作。那么问题来,python中有没有这个数据类型呢?答案是肯定有的,它就是命名元组(namedtyple)。
首先来看一下python中普通元组的不方便之处:
Bob=("bob",30,'male')#如果想知道Bobde 名字,则需要使用索引位置进行读取,如下name=Bob[0]for people in [Bob]: print("%s is %d years old %s" % peole)#显示结果bob is 30 years old male
1、namedtuple基础
通过上面的例子,访问元祖数据的时候是通过索引下标来操作的,对此需要熟记每个下标对应的具体含义,如果元祖有成千上百个数据,那么想记住每个下标对应的意义那是相当困难的,于是就出现了命名元祖namedtuple。
namedtuple对象的定义如以下格式:
collections.namedtuple(typename, field_names, verbose=False, rename=False)
返回一个命名元祖子类typename,其中参数的意义如下:
typename,:此元组的名称;
field_names: 元祖中元素的名称(类似于c结构体中的age等),此字段有多种表达方式,见例子;
rename:如果元素名称中含有python的关键字,则必须设置为rename=True,具体见下面;
verbose:默认就好;
举个小例子,加深一下自己的理解:
import collections#其中field_names 有多种表达方式,如下student=collections.namedtuple('student','name age sex')student=cpllections.namedtuple('student',['name','age','sex'])student=cpllections.namedtuple('student','name,age,sex')spark=student(name='sunYang',age=20,sex='male')print(spark)print("spark's name is %s" % spark.name)print("%s is %d years old %s" % spark)显示结果如下:student(name='sunYang', age=20, sex='male')spark's name is sunYangsunYang is 20 years old male
通过上面的例子 其中student是元祖名称,‘name age sex’是元组总元素名称,用空格隔开,我们访问元祖对象中的元素时可以使用逗号操作符(.)读取对象中某个感兴趣的元素,而不必像原始元组中,需要记录下标代表的元素含义。
下面了解一下rename参数的作用:
import collections with_class=collections.namedtuple('Person','name age class gender',rename=True) print with_class._fields two_ages=collections.namedtuple('Person','name age gender age',rename=True) print two_ages._fields其输出结果为: ('name', 'age', '_2', 'gender') ('name', 'age', 'gender', '_3')
我们使用rename=True的方式打开重命名选项。
可以看到第一个集合中的class被重命名为 ‘2′ ; 第二个集合中重复的age被重命名为 ‘_3′;这是因为namedtuple在重命名的时候使用了下划线 加元素所在索引数的方式进行重命名。
2、namedtuple高级用法
我们通过定义一个命名元组,如下:
Point = namedtuple(‘Point’, [‘x’, ‘y’], verbose=True)
那么Point是一个元祖的子类,类结构具体如下:
class Point(tuple): 'Point(x, y)' __slots__ = () _fields = ('x', 'y') def __new__(_cls, x, y): 'Create new instance of Point(x, y)' return _tuple.__new__(_cls, (x, y)) @classmethod def _make(cls, iterable, new=tuple.__new__, len=len): 'Make a new Point object from a sequence or iterable' result = new(cls, iterable) if len(result) != 2: raise TypeError('Expected 2 arguments, got %d' % len(result)) return result def __repr__(self): 'Return a nicely formatted representation string' return 'Point(x=%r, y=%r)' % self def _asdict(self): 'Return a new OrderedDict which maps field names to their values' return OrderedDict(zip(self._fields, self)) def _replace(_self, **kwds): 'Return a new Point object replacing specified fields with new values' result = _self._make(map(kwds.pop, ('x', 'y'), _self)) if kwds: raise ValueError('Got unexpected field names: %r' % kwds.keys()) return result def __getnewargs__(self): 'Return self as a plain tuple. Used by copy and pickle.' return tuple(self) __dict__ = _property(_asdict) def __getstate__(self): 'Exclude the OrderedDict from pickling' pass x = _property(_itemgetter(0), doc='Alias for field number 0') y = _property(_itemgetter(1), doc='Alias for field number 1')
- python 命名元组(namedtuple)
- python 命名元组(namedtuple)
- python学习笔记--命名元组(Namedtuple)
- 命名元组 collections.namedtuple
- Python namedtuple 具名元组
- 自定义命名的元组collections.namedtuple
- python 2-2 如何为元组中的每个元素命名, 提高程序可读性-collections.namedtuple
- 5.3.5 namedtuple() 创建命名字段的元组结构
- Python中字典、列表、元组相关知识持续整理-namedtuple
- Python之命名元组
- Python namedtuple
- python namedtuple
- Python namedtuple
- python namedtuple
- defaultdict 和 namedtuple 的使用(python)
- Python namedtuple 用法
- Python-namedtuple,enum
- Python namedtuple使用详解
- MCIMX6Q-SDB 试用简介1
- 前台 JSON对象转换成字符串 相互转换 的几种方式
- 数据归一化的作用--在svm 训练的时候特别有用
- fastboot timeout
- hdu 1028
- python 命名元组(namedtuple)
- 解析json串
- 几个常用的NLP网站
- ExtJS4 grid单元格添加复选框
- 【腾讯TMQ】压力测试遭遇大量TIME_WAIT之后
- 1298 圆与三角形(基础几何知识)
- C++ 获取凌晨/月初 时间戳
- java IO流之三 使用缓冲流来读写文件
- Adapter中onItemClick方法中的四个参数解析