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 creating a single view of multiple mappings
Counter dict subclass for counting hashable objects
OrderedDict dict subclass that remembers the order entries were added
defaultdict dict subclass that calls a factory function to supply missing values
UserDict wrapper around dictionary objects for easier dict subclassing
UserList wrapper around list objects for easier list subclassing
UserString wrapper around string objects for easier string subclassing

namedtuple()

tuple类似于数组,只能通过下表来访问各个元素。使用namedtuple,每个元素有自己的名字,数据的意义一目了然。

In [22]: from collections import namedtuple

In [23]: Point = namedtuple(‘Point‘, [‘x‘, ‘y‘])

In [24]: p = Point(11, y=22)

In [25]: p[0] + p[1]
Out[25]: 33

In [26]: p.x
Out[26]: 11

In [27]: p.y
Out[27]: 22

In [28]: p
Out[28]: Point(x=11, y=22)

In [29]: x, y = p

In [30]: x
Out[30]: 11

命名元组还有三种额外的方法,两个属性

classmethod somenamedtuple._make(iterable)

  Class method that makes a new instance from an existing sequence or iterable.

  从一个已经存在的序列或可迭代对象创建一个新实例

In [1]: from collections import namedtuple

In [2]: Point = namedtuple(‘Point‘, [‘x‘, ‘y‘, ‘z‘])

In [3]: t = [1, 2, 3]

In [4]: p = Point._make(t)

In [5]: p
Out[5]: Point(x=1, y=2, z=3)

somenamedtuple._asdict()

  Return a new OrderedDict which maps field names to their corresponding values:

  返回一个新的OrderedDict,并以field names作为key, field names对应值作为values。

In [16]: from collections import namedtuple

In [17]: Point = namedtuple(‘Point‘, [‘x‘, ‘y‘, ‘z‘])

In [18]: t = [1, 2, 3]

In [19]: p = Point._make(t)

In [20]: p
Out[20]: Point(x=1, y=2, z=3)

In [21]: d = p._asdict()

In [22]: d.get(‘x‘)
Out[22]: 1

In [23]: d
Out[23]: OrderedDict([(‘x‘, 1), (‘y‘, 2), (‘z‘, 3)])

somenamedtuple._replace(kwargs)

  Return a new instance of the named tuple replacing specified fields with new values:

  返回一个用新值替换指定字段后的命名元组的一个新实例。

In [24]: from collections import namedtuple

In [25]: Point = namedtuple(‘Point‘, [‘x‘, ‘y‘, ‘z‘])

In [26]: t = [1, 2, 3]

In [27]: p = Point._make(t)

In [28]: p
Out[28]: Point(x=1, y=2, z=3)

In [29]: p._replace(z=4)
Out[29]: Point(x=1, y=2, z=4)

In [30]: p.z
Out[30]: 3

In [31]: p = p._replace(z=4)

In [33]: p.z
Out[33]: 4

In [34]: p
Out[34]: Point(x=1, y=2, z=4)

somenamedtuple._fields

  Tuple of strings listing the field names. Useful for introspection and for creating new named tuple types from existing named tuples.

  字段名列表

In [35]: p._fields
Out[35]: (‘x‘, ‘y‘, ‘z‘)

somenamedtuple._source

  A string with the pure Python source code used to create the named tuple class. The source makes the named tuple self-documenting. It can be printed, executed using exec(), or saved to a file and imported.

  创建命名元组的纯python代码

In [36]: p._source
Out[36]: "from builtins import property as _property, tuple as _tuple\nfrom operator import itemgetter as _itemgetter\nfrom collections import OrderedDict\n\nclass Point(tuple):\n    ‘Point(x, y, z)‘\n\n    __slots__ = ()\n\n    _fields = (‘x‘, ‘y‘, ‘z‘)\n\n    def __new__(_cls, x, y, z):\n        ‘Create new instance of Point(x, y, z)‘\n        return _tuple.__new__(_cls, (x, y, z))\n\n    @classmethod\n    def _make(cls, iterable, new=tuple.__new__, len=len):\n        ‘Make a new Point object from a sequence or iterable‘\n        result = new(cls, iterable)\n        if len(result) != 3:\n            raise TypeError(‘Expected 3 arguments, got %d‘ % len(result))\n        return result\n\n    def _replace(_self, **kwds):\n        ‘Return a new Point object replacing specified fields with new values‘\n        result = _self._make(map(kwds.pop, (‘x‘, ‘y‘, ‘z‘), _self))\n        if kwds:\n            raise ValueError(‘Got unexpected field names: %r‘ % list(kwds))\n        return result\n\n    def __repr__(self):\n        ‘Return a nicely formatted representation string‘\n        return self.__class__.__name__ + ‘(x=%r, y=%r, z=%r)‘ % self\n\n    def _asdict(self):\n        ‘Return a new OrderedDict which maps field names to their values.‘\n        return OrderedDict(zip(self._fields, self))\n\n    def __getnewargs__(self):\n        ‘Return self as a plain tuple.  Used by copy and pickle.‘\n        return tuple(self)\n\n    x = _property(_itemgetter(0), doc=‘Alias for field number 0‘)\n\n    y = _property(_itemgetter(1), doc=‘Alias for field number 1‘)\n\n    z = _property(_itemgetter(2), doc=‘Alias for field number 2‘)\n\n"

  

时间: 2025-01-04 19:26:11

python namedtuple(命名元组)的相关文章

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():命名元组函数赋予元组中每个位置的含义,并允许更具可读性的自编写代码.它们可以在任何使用常规元组的地方使用,并且可以通过名称而不是位置索引来添加字段. 实例: from collections import namedtupleStudent=namedtuple('Student',['name','age','sex','email']) 第一个参数为设置创建子类的名字,创建一个Student类的元组子类. 方法返回的就是一个元组的子类.s=Student(

python 命名元组(namedtuple)

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

Python冷知识之命名元组

元组tuple:在Python数据类型中属于不可变数据类型 命名元组:namedtuples:是python中的元组数据类型的扩展 普通元组中的数据只能通过索引(index)来访问 命名元组:可以通过唯一标识符来访问存储的数据,(名字.对象) 使用: 导入 from collection import namedtuple 定义: In [11]: Car = namedtuple('Car', 'color size mileage') In [12]: mycar = Car('red','

Python学习—常用时间类与命名元组

常用时间类与命名元组 1. 常用时间类date 日期类time 时间类datetimetimedelat 时间间隔2. 一些术语和约定的解释:1.时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日开始按秒计算的偏移量(time.gmtime(0))此模块中的函数无法处理1970纪元年以前的时间或太遥远的未来(处理极限取决于C函数库,对于32位系统而言,是2038年)2.UTC(Coordinated Universal Time,世界协调时)也叫格林威治天文时间,是

Python collections系列之可命名元组

可命名元组(namedtuple)  根据nametuple可以创建一个包含tuple所有功能以及其他功能的类 1.创建一个坐标类 import collections # 创建类, defaultdict,坐标中会使用 MytupleClass = collections.namedtuple('MytupleClass',['x', 'y', 'z']) obj = MytupleClass(11, 22, 33) 2.查询类中的x,y,z坐标 # 默认情况下元组只能使用索引进行访问,通过创

namedtuple可命名元组

import collections as con #用namedtyuple创建一个类 classtuple = con.namedtuple('classtuple', ['x', 'y', 'z']) #用这个类创建可命名元组对象 namet= classtuple(1,2,3) print (namet.x,namet.y,namet.z)

可命名元组

'''对于可命名元组,Python没有创建类,我们需要自己创建一个类'''import collections'''创建一个类 '''yuanzu=collections.namedtuple('y',['x','y','z'])o=yuanzu(1,2,4)print(o.x) 可命名元组相对简单