最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中命名元組Namedtuple的使用詳解

 更新時(shí)間:2023年09月10日 10:00:51   作者:python收藏家  
Python支持一種名為“namedtuple()”的容器字典,它存在于模塊“collections”中,下面就跟隨小編一起學(xué)習(xí)一下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()的屬性值是有序的,可以使用索引號(hào)訪問,不像字典不能通過索引訪問。

按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ù)傳遞的可迭代對(duì)象返回namedtuple()。

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

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

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

__ new __():這個(gè)函數(shù)返回一個(gè)類的新實(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)建一個(gè)新的namedtuple類。第一個(gè)參數(shù)是新類的名稱,第二個(gè)參數(shù)是字段名稱列表。

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

代碼定義了一個(gè)名為Point的命名元組,其中包含兩個(gè)字段x和y。然后創(chuàng)建Point類的實(shí)例,其中x=1和y=2,并打印其x和y屬性。

時(shí)間復(fù)雜度:

訪問命名元組的屬性的時(shí)間復(fù)雜度是O(1),因?yàn)樗且粋€(gè)簡單的屬性查找。因此,打印p.x和p.y的時(shí)間復(fù)雜度都是O(1)。

空間復(fù)雜度:

代碼的空間復(fù)雜度是O(1),因?yàn)樗环峙淙魏纬雒M實(shí)例p和Point類定義所需的額外內(nèi)存。

總的來說,代碼具有恒定的時(shí)間和空間復(fù)雜度。

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

相關(guān)文章

  • pytorch-gpu安裝的經(jīng)驗(yàn)與教訓(xùn)

    pytorch-gpu安裝的經(jīng)驗(yàn)與教訓(xùn)

    本文主要介紹了pytorch-gpu安裝的經(jīng)驗(yàn)與教訓(xùn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2023-01-01
  • Python刪除字典中的某個(gè)key的常用方法

    Python刪除字典中的某個(gè)key的常用方法

    字典是Python中的一種數(shù)據(jù)類型,它是一個(gè)無序的鍵值對(duì)集合,在實(shí)際的編程中,我們經(jīng)常需要?jiǎng)h除字典中的某個(gè)鍵值對(duì),本文將從多個(gè)角度分析Python刪除字典中的某個(gè)key的方法,需要的朋友可以參考下
    2024-10-10
  • 基于Python實(shí)現(xiàn)Word文檔與SVG格式的相互轉(zhuǎn)換

    基于Python實(shí)現(xiàn)Word文檔與SVG格式的相互轉(zhuǎn)換

    Word和SVG是兩種常見的文件格式,各自有不同的應(yīng)用場景,在實(shí)際應(yīng)用中,我們可能需要將Word文檔內(nèi)容轉(zhuǎn)換為SVG圖形用于網(wǎng)頁展示,或者將 SVG圖形嵌入到Word文檔中進(jìn)行編輯和排版,這篇博客將探討如何使用Python實(shí)現(xiàn)Word與SVG 格式的相互轉(zhuǎn)換,需要的朋友可以參考下
    2025-02-02
  • Pandas?Matplotlib保存圖形時(shí)坐標(biāo)軸標(biāo)簽太長導(dǎo)致顯示不全問題的解決

    Pandas?Matplotlib保存圖形時(shí)坐標(biāo)軸標(biāo)簽太長導(dǎo)致顯示不全問題的解決

    在使用matplotlib作圖的時(shí)候,有的時(shí)候會(huì)遇到畫圖時(shí)顯示不全和圖片保存時(shí)不完整的問題,這篇文章主要給大家介紹了關(guān)于Pandas?Matplotlib保存圖形時(shí)坐標(biāo)軸標(biāo)簽太長導(dǎo)致顯示不全問題的解決方法,需要的朋友可以參考下
    2022-06-06
  • Python鍵鼠操作自動(dòng)化庫PyAutoGUI簡介(小結(jié))

    Python鍵鼠操作自動(dòng)化庫PyAutoGUI簡介(小結(jié))

    這篇文章主要介紹了Python鍵鼠操作自動(dòng)化庫PyAutoGUI簡介,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • Python自動(dòng)化測試框架:unittest、pytest、Selenium、requests和Pytest-BDD

    Python自動(dòng)化測試框架:unittest、pytest、Selenium、requests和Pytest-BDD

    本文介紹了Python中幾種常見的自動(dòng)化測試框架,包括unittest、pytest、Selenium、requests和 Pytest-BDD,以及各自的優(yōu)缺點(diǎn)和適用場景,通過實(shí)戰(zhàn)案例幫助開發(fā)者編寫高質(zhì)量的測試代碼,提高代碼質(zhì)量
    2026-05-05
  • Django實(shí)現(xiàn)任意文件上傳(最簡單的方法)

    Django實(shí)現(xiàn)任意文件上傳(最簡單的方法)

    這篇文章主要介紹了Django實(shí)現(xiàn)任意文件上傳,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-06-06
  • 詳解opencv?rtsp?硬件解碼

    詳解opencv?rtsp?硬件解碼

    這篇文章主要介紹了opencv rtsp硬件解碼的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-08-08
  • python創(chuàng)建ArcGIS shape文件的實(shí)現(xiàn)

    python創(chuàng)建ArcGIS shape文件的實(shí)現(xiàn)

    今天小編就為大家分享一篇python創(chuàng)建ArcGIS shape文件的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • 基于Python制作一個(gè)文件解壓縮工具

    基于Python制作一個(gè)文件解壓縮工具

    經(jīng)常由于各種壓縮格式的不一樣用到文件的解壓縮時(shí)就需要下載不同的解壓縮工具去處理不同的文件。本文將用Python制作一個(gè)解壓縮小工具,以后再也不用下載各種格式的解壓縮軟件了
    2022-05-05

最新評(píng)論

南溪县| 肇东市| 荆州市| 灵武市| 东宁县| 望都县| 陇川县| 大足县| 晋州市| 株洲县| 洛浦县| 江山市| 尼勒克县| 宜州市| 大石桥市| 民权县| 山东省| 高清| 集安市| 时尚| 宿州市| 磐安县| 河间市| 冀州市| 建宁县| 榆林市| 南雄市| 青冈县| 紫阳县| 宜春市| 巴塘县| 贺州市| 叙永县| 瑞安市| 眉山市| 女性| 平山县| 苗栗县| 景泰县| 内乡县| 茂名市|