Python中的命名元组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')

使用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类定义所需的额外内存。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值