欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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作為其參數(shù)來訪問值的方法。

# 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. 轉(zhuǎn)換操作

_make():此函數(shù)用于從作為參數(shù)傳遞的可迭代對象返回namedtuple()。

_asdict():此函數(shù)返回根據(jù)namedtuple()的映射值構(gòu)造的OrderedDict()。

使用 “**”(星星)運算符:這個函數(shù)用于將字典轉(zhuǎn)換為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:這個數(shù)據(jù)屬性用于獲取聲明的命名空間的所有鍵名。

_replace():_replace()類似于str.replace(),但針對命名字段(不修改原始值)

__ new __():這個函數(shù)返回一個類的新實例,通過獲取我們想要分配給命名元組中的鍵的值。

__ getnewargs __():此函數(shù)將命名元組作為普通元組返回。

# 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()函數(shù)創(chuàng)建一個新的namedtuple類。第一個參數(shù)是新類的名稱,第二個參數(shù)是字段名稱列表。

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。然后創(chuàng)建Point類的實例,其中x=1和y=2,并打印其x和y屬性。

時間復雜度:

訪問命名元組的屬性的時間復雜度是O(1),因為它是一個簡單的屬性查找。因此,打印p.x和p.y的時間復雜度都是O(1)。

空間復雜度:

代碼的空間復雜度是O(1),因為它不分配任何超出命名元組實例p和Point類定義所需的額外內(nèi)存。

總的來說,代碼具有恒定的時間和空間復雜度。

到此這篇關(guān)于Python中命名元組Namedtuple的使用詳解的文章就介紹到這了,更多相關(guān)Python命名元組Namedtuple內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論