📜  Python中的命名元组

📅  最后修改于: 2022-05-13 01:54:23.107000             🧑  作者: Mango

Python中的命名元组

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

例子:

Python3
# Python code to demonstrate namedtuple()
 
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)


Python3
# Python code to demonstrate namedtuple() and
# Access by name, index and getattr()
 
# importing "collections" for namedtuple()
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'))


Python3
# 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))


Python3
# Python code to demonstrate namedtuple() and
# _fields and _replace()
 
# importing "collections" for namedtuple()
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)


输出:

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

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

访问操作

  • 按索引访问: namedtuple() 的属性值是有序的,可以使用索引号访问,不像字典不能按索引访问。
  • 通过键名访问:也允许通过键名访问,就像在字典中一样。
  • 使用 getattr():这是通过将 namedtuple 和键值作为参数来访问值的另一种方法。

Python3

# Python code to demonstrate namedtuple() and
# Access by name, index and getattr()
 
# importing "collections" for namedtuple()
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

转换操作

  • _make() :-此函数用于从作为参数传递的可迭代对象中返回一个 namedtuple()
  • _asdict() :-此函数返回OrderedDict()namedtuple() 的映射值构成。
  • 使用“**”(双星)运算符:- 此函数用于将字典转换为 namedtuple()。

Python3

# 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')

附加操作

  • _fields:该函数用于返回声明的命名空间的所有键名
  • _replace(): _replace() 类似于 str.replace() 但目标命名字段(不修改原始值)

Python3

# Python code to demonstrate namedtuple() and
# _fields and _replace()
 
# importing "collections" for namedtuple()
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)

输出 :

All the fields of students are : 
('name', 'age', 'DOB')
The modified namedtuple is : 
Student(name='Manjeet', age='19', DOB='2541997')