Python中namedtuple具名元组的简单使用

编程入门 行业动态 更新时间:2024-10-09 04:25:46

Python中namedtuple具名元组的<a href=https://www.elefans.com/category/jswz/34/1770983.html style=简单使用"/>

Python中namedtuple具名元组的简单使用

参考链接: Python namedtuple
参考链接: namedtuple() 命名元组的工厂函数

一下内容摘自菜鸟教程runoob:

Python元组的升级版本 -- namedtuple(具名元组)因为元组的局限性:不能为元组内部的数据进行命名,
所以往往我们并不知道一个元组所要表达的意义,
所以在这里引入了 collections.namedtuple 这个工厂函数,
来构造一个带字段名的元组。具名元组的实例和普通元组消耗的内存一样多,
因为字段名都被存在对应的类里面。
这个类跟普通的对象实例比起来也要小一些,
因为 Python 不会用 __dict__ 来存放这些实例的属性。
namedtuple 对象的定义如以下格式:
collections.namedtuple(typename, field_names, verbose=False, rename=False) 

collections.namedtuple(typename, field_names, verbose=False, rename=False)

  • 返回一个具名元组子类 typename,其中参数的意义如下:
    • typename:元组名称
    • field_names: 元组中元素的名称
    • rename: 如果元素名称中含有 python 的关键字,则必须设置为 rename=True
    • verbose: 默认就好

collections.namedtuple('User', 'name age id') 创建一个具名元组, 需要两个参数,一个是类名,另一个是类的各个字段名。 后者可以是有多个字符串组成的可迭代对象, 或者是有空格分隔开的字段名组成的字符串(比如本示例)。 具名元组可以通过字段名或者位置来获取一个字段的信息。

类属性 _fields:包含这个类所有字段名的元组 类方法 _make(iterable):接受一个可迭代对象来生产这个类的实例 实例方法 _asdict():把具名元组以 collections.OrdereDict 的形式返回,可以利用它来把元组里的信息友好的展示出来。

实验演示1:

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import collections
>>> from collections import namedtuple
>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)     # instantiate with positional or keyword arguments
>>> p[0]
11
>>> p[1]
22
>>> p.x
11
>>> p.y
22
>>> p[0] + p[1]             # indexable like the plain tuple (11, 22)
33
>>> x, y = p                # unpack like a regular tuple
>>> x, y
(11, 22)
>>> p.x + p.y               # fields also accessible by name
33
>>> p                       # readable __repr__ with a name=value style
Point(x=11, y=22)
>>> 
>>> # 从存在的序列或迭代实例创建一个新实例。
>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)
>>> 
>>> 
>>> 
>>> # Return a new OrderedDict which maps field names to their corresponding values:
>>> p._asdict()
OrderedDict([('x', 11), ('y', 22)])
>>> 
>>> 
>>> p
Point(x=11, y=22)
>>> p._replace(x=33)
Point(x=33, y=22)
>>> p
Point(x=11, y=22)
>>> 
>>> 
>>> p._fields            # view the field names
('x', 'y')
>>> 
>>> getattr(p, 'x') # 获取这个名字域的值,使用 getattr() 函数 :
11
>>> 
>>> 
>>> Color = namedtuple('Color', 'red green blue')
>>> p._fields            # view the field names
('x', 'y')
>>> Color._fields
('red', 'green', 'blue')
>>> Pixel = namedtuple('Pixel', Point._fields + Color._fields)
>>> Pixel._fields
('x', 'y', 'red', 'green', 'blue')
>>> Pixel(11, 22, 128, 255, 0)
Pixel(x=11, y=22, red=128, green=255, blue=0)
>>> 
>>> 

实验演示2:

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> import collections
>>> from collections import namedtuple
>>> # 两种方法来给 namedtuple 定义方法名
>>> # User = collections.namedtuple('User', ['name', 'age', 'id'])
>>> # User = collections.namedtuple('User', 'name age id')
>>> Person = collections.namedtuple('Friend4cxq', 'name age id')
>>> p = Person('tester', '22', '464643123')
>>> p
Friend4cxq(name='tester', age='22', id='464643123')
>>> Friend4cxq = Person
>>> p = Friend4cxq('昊昊', '55', '123')
>>> p
Friend4cxq(name='昊昊', age='55', id='123')
>>> 
>>> 
>>> 
>>> 
>>> Friend4cxq = collections.namedtuple('Friend4cxq', ['name', 'age', 'gender'])
>>> hh = Friend4cxq('haohao',33,'male')
>>> hh
Friend4cxq(name='haohao', age=33, gender='male')
>>> print(hh)
Friend4cxq(name='haohao', age=33, gender='male')
>>> 
>>> yzb = Friend4cxq(name='宝儿', age=88, gender='男')
>>> yzb
Friend4cxq(name='宝儿', age=88, gender='男')
>>> 
>>> 
>>> # 获取所有字段名
>>> print( yzb._fields )
('name', 'age', 'gender')
>>> 
>>> 
>>> # 也可以通过一个list来创建一个User对象,这里注意需要使用"_make"方法
>>> cjh = Friend4cxq._make(['金涵', 12,'男子'])
>>> cjh
Friend4cxq(name='金涵', age=12, gender='男子')
>>> cjh.name
'金涵'
>>> cjh.age
12
>>> cjh.gender
'男子'
>>> # 以上用于获取用户的属性
>>> 
>>> 
>>> # 修改对象属性,注意要使用"_replace"方法
>>> cjh._replace(gender='男性')
Friend4cxq(name='金涵', age=12, gender='男性')
>>> cjh
Friend4cxq(name='金涵', age=12, gender='男子')
>>> cjh = cjh._replace(gender='男性')
>>> cjh
Friend4cxq(name='金涵', age=12, gender='男性')
>>> 
>>> 
>>> 
>>> 
>>> 
>>> # 将User对象转换成字典,注意要使用"_asdict"
>>> print( cjh._asdict() )
OrderedDict([('name', '金涵'), ('age', 12), ('gender', '男性')])
>>> 

更多推荐

Python中namedtuple具名元组的简单使用

本文发布于:2024-02-13 04:53:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1690764.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简单   Python   namedtuple

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!