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進(jìn)行訪問。
使用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()。
使用 “**”(星星)運(yùn)算符:這個函數(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ù)返回一個類的新實(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類的實(shí)例,其中x=1和y=2,并打印其x和y屬性。
時間復(fù)雜度:
訪問命名元組的屬性的時間復(fù)雜度是O(1),因?yàn)樗且粋€簡單的屬性查找。因此,打印p.x和p.y的時間復(fù)雜度都是O(1)。
空間復(fù)雜度:
代碼的空間復(fù)雜度是O(1),因?yàn)樗环峙淙魏纬雒M實(shí)例p和Point類定義所需的額外內(nèi)存。
總的來說,代碼具有恒定的時間和空間復(fù)雜度。
到此這篇關(guān)于Python中命名元組Namedtuple的使用詳解的文章就介紹到這了,更多相關(guān)Python命名元組Namedtuple內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Django項(xiàng)目如何給數(shù)據(jù)庫添加約束
這篇文章主要介紹了Django項(xiàng)目如何給數(shù)據(jù)庫添加約束,幫助大家更好的理解和學(xué)習(xí)使用Django框架,感興趣的朋友可以了解下2021-04-04
Python趣味挑戰(zhàn)之給幼兒園弟弟生成1000道算術(shù)題
為了讓弟弟以后好好學(xué)習(xí),我特地用Python給他生成了1000道算術(shù)題讓他做,他以后一定會感謝我的!文中有非常詳細(xì)的代碼示例,需要的朋友可以參考下2021-05-05
Django自關(guān)聯(lián)實(shí)現(xiàn)多級聯(lián)動查詢實(shí)例
這篇文章主要介紹了Django自關(guān)聯(lián)實(shí)現(xiàn)多級聯(lián)動查詢實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05
python字符串和常用數(shù)據(jù)結(jié)構(gòu)知識總結(jié)
在本文中我們系統(tǒng)的給大家整理了關(guān)于python字符串和常用數(shù)據(jù)結(jié)構(gòu)的相關(guān)知識點(diǎn)以及實(shí)例代碼,需要的朋友們學(xué)習(xí)下。2019-05-05
Python編程實(shí)現(xiàn)輸入某年某月某日計算出這一天是該年第幾天的方法
這篇文章主要介紹了Python編程實(shí)現(xiàn)輸入某年某月某日計算出這一天是該年第幾天的方法,涉及Python針對日期時間的轉(zhuǎn)換與運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-04-04
如何使用python轉(zhuǎn)移mysql數(shù)據(jù)庫中的全部數(shù)據(jù)
這篇文章主要為大家詳細(xì)介紹了如何使用python轉(zhuǎn)移mysql數(shù)據(jù)庫中的全部數(shù)據(jù),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解下2024-11-11

