Python中命名元组Namedtuple的使用详解

 更新时间:2023年09月10日 10:00:51   作者:python收藏家  
Python支持一种名为“namedtuple()”的容器字典,它存在于模块“collections”中,下面就跟随小编一起学习一下Namedtuple的具体使用吧

Python支持一种名为“namedtuple()”的容器字典,它存在于模块“collections”中。像字典一样,它们包含散列为特定值的键。但恰恰相反,它支持从键值和迭代访问,这是字典所缺乏的功能。

示例:

from collections import namedtuple
# Declaring namedtuple()
Student = namedtuple('Student', ['name', 'age', 'DOB'])
# Adding values
S = Student('Nandini', '19', '2541997')
# Access using index
print("The Student age using index is : ", end="")
print(S[1])
# Access using name
print("The Student name using keyname is : ", end="")
print(S.name)

输出

The Student age using index is : 19
The Student name using keyname is : Nandini

让我们看看namedtuple()上的各种操作。

1. 访问操作

按索引访问:namedtuple()的属性值是有序的,可以使用索引号访问,不像字典不能通过索引访问。

按key访问:在字典中也允许通过key进行访问。

使用getattr():这是另一种通过提供namedtuple和key value作为其参数来访问值的方法。

# Python code to demonstrate namedtuple() and
# Access by name, index and getattr()
import collections
# Declaring namedtuple()
Student = collections.namedtuple('Student', ['name', 'age', 'DOB'])
# Adding values
S = Student('Nandini', '19', '2541997')
# Access using index
print("The Student age using index is : ", end="")
print(S[1])
# Access using name
print("The Student name using keyname is : ", end="")
print(S.name)
# Access using getattr()
print("The Student DOB using getattr() is : ", end="")
print(getattr(S, 'DOB'))

输出

The Student age using index is : 19
The Student name using keyname is : Nandini
The Student DOB using getattr() is : 2541997

2. 转换操作

_make():此函数用于从作为参数传递的可迭代对象返回namedtuple()。

_asdict():此函数返回根据namedtuple()的映射值构造的OrderedDict()。

使用 “**”(星星)运算符:这个函数用于将字典转换为namedtuple()。

# Python code to demonstrate namedtuple() and
# _make(), _asdict() and "**" operator
# importing "collections" for namedtuple()
import collections
# Declaring namedtuple()
Student = collections.namedtuple('Student',
								['name', 'age', 'DOB'])
# Adding values
S = Student('Nandini', '19', '2541997')
# initializing iterable
li = ['Manjeet', '19', '411997']
# initializing dict
di = {'name': "Nikhil", 'age': 19, 'DOB': '1391997'}
# using _make() to return namedtuple()
print("The namedtuple instance using iterable is : ")
print(Student._make(li))
# using _asdict() to return an OrderedDict()
print("The OrderedDict instance using namedtuple is : ")
print(S._asdict())
# using ** operator to return namedtuple from dictionary
print("The namedtuple instance from dict is : ")
print(Student(**di))

输出

The namedtuple instance using iterable is  : 
Student(name='Manjeet', age='19', DOB='411997')
The OrderedDict instance using namedtuple is  : 
OrderedDict([('name', 'Nandini'), ('age', '19'), ('DOB', '2541997')])
The namedtuple instance from dict is  : 
Student(name='Nikhil', age=19, DOB='1391997')

3. 附加操作

_fields:这个数据属性用于获取声明的命名空间的所有键名。

_replace():_replace()类似于str.replace(),但针对命名字段(不修改原始值)

__ new __():这个函数返回一个类的新实例,通过获取我们想要分配给命名元组中的键的值。

__ getnewargs __():此函数将命名元组作为普通元组返回。

# Python code to demonstrate namedtuple() and
# _fields and _replace()
import collections
# Declaring namedtuple()
Student = collections.namedtuple('Student', ['name', 'age', 'DOB'])
# Adding values
S = Student('Nandini', '19', '2541997')
# using _fields to display all the keynames of namedtuple()
print("All the fields of students are : ")
print(S._fields)
# ._replace returns a new namedtuple, it does not modify the original
print("returns a new namedtuple : ")
print(S._replace(name='Manjeet'))
# original namedtuple
print(S)
# Student.__new__ returns a new instance of Student(name,age,DOB)
print(Student.__new__(Student,'Himesh','19','26082003'))
H=Student('Himesh','19','26082003')
# .__getnewargs__ returns the named tuple as a plain tuple
print(H.__getnewargs__())

输出

All the fields of students are : 
('name', 'age', 'DOB')
returns a new namedtuple : 
Student(name='Manjeet', age='19', DOB='2541997')
Student(name='Nandini', age='19', DOB='2541997')
Student(name='Himesh', age='19', DOB='26082003')
('Himesh', '19', '26082003')

4.使用collections模块

这种方法使用collections模块中的namedtuple()函数创建一个新的namedtuple类。第一个参数是新类的名称,第二个参数是字段名称列表。

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(x=1, y=2)
print(p.x, p.y) # Output: 1 2

代码定义了一个名为Point的命名元组,其中包含两个字段x和y。然后创建Point类的实例,其中x=1和y=2,并打印其x和y属性。

时间复杂度:

访问命名元组的属性的时间复杂度是O(1),因为它是一个简单的属性查找。因此,打印p.x和p.y的时间复杂度都是O(1)。

空间复杂度:

代码的空间复杂度是O(1),因为它不分配任何超出命名元组实例p和Point类定义所需的额外内存。

总的来说,代码具有恒定的时间和空间复杂度。

到此这篇关于Python中命名元组Namedtuple的使用详解的文章就介绍到这了,更多相关Python命名元组Namedtuple内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • pytorch-gpu安装的经验与教训

    pytorch-gpu安装的经验与教训

    本文主要介绍了pytorch-gpu安装的经验与教训,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2023-01-01
  • Python删除字典中的某个key的常用方法

    Python删除字典中的某个key的常用方法

    字典是Python中的一种数据类型,它是一个无序的键值对集合,在实际的编程中,我们经常需要删除字典中的某个键值对,本文将从多个角度分析Python删除字典中的某个key的方法,需要的朋友可以参考下
    2024-10-10
  • 基于Python实现Word文档与SVG格式的相互转换

    基于Python实现Word文档与SVG格式的相互转换

    Word和SVG是两种常见的文件格式,各自有不同的应用场景,在实际应用中,我们可能需要将Word文档内容转换为SVG图形用于网页展示,或者将 SVG图形嵌入到Word文档中进行编辑和排版,这篇博客将探讨如何使用Python实现Word与SVG 格式的相互转换,需要的朋友可以参考下
    2025-02-02
  • Pandas Matplotlib保存图形时坐标轴标签太长导致显示不全问题的解决

    Pandas Matplotlib保存图形时坐标轴标签太长导致显示不全问题的解决

    在使用matplotlib作图的时候,有的时候会遇到画图时显示不全和图片保存时不完整的问题,这篇文章主要给大家介绍了关于Pandas Matplotlib保存图形时坐标轴标签太长导致显示不全问题的解决方法,需要的朋友可以参考下
    2022-06-06
  • Python键鼠操作自动化库PyAutoGUI简介(小结)

    Python键鼠操作自动化库PyAutoGUI简介(小结)

    这篇文章主要介绍了Python键鼠操作自动化库PyAutoGUI简介,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-05-05
  • Python自动化测试框架:unittest、pytest、Selenium、requests和Pytest-BDD

    Python自动化测试框架:unittest、pytest、Selenium、requests和Pytest-BDD

    本文介绍了Python中几种常见的自动化测试框架,包括unittest、pytest、Selenium、requests和 Pytest-BDD,以及各自的优缺点和适用场景,通过实战案例帮助开发者编写高质量的测试代码,提高代码质量
    2026-05-05
  • Django实现任意文件上传(最简单的方法)

    Django实现任意文件上传(最简单的方法)

    这篇文章主要介绍了Django实现任意文件上传,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-06-06
  • 详解opencv rtsp 硬件解码

    详解opencv rtsp 硬件解码

    这篇文章主要介绍了opencv rtsp硬件解码的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-08-08
  • python创建ArcGIS shape文件的实现

    python创建ArcGIS shape文件的实现

    今天小编就为大家分享一篇python创建ArcGIS shape文件的实现,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-12-12
  • 基于Python制作一个文件解压缩工具

    基于Python制作一个文件解压缩工具

    经常由于各种压缩格式的不一样用到文件的解压缩时就需要下载不同的解压缩工具去处理不同的文件。本文将用Python制作一个解压缩小工具,以后再也不用下载各种格式的解压缩软件了
    2022-05-05

最新评论