具名元組來自 Python 內(nèi)置庫 collections.nametupled 中, 可以用來構(gòu)建帶字段名的元組和一個(gè)相應(yīng)的類collections.namedtuple 是一個(gè)工廠函數(shù)镣衡,它可以用來構(gòu)建一個(gè)帶字段名的元組和一個(gè)有名字的類——這個(gè)帶字的類對(duì)調(diào)試程序有很大幫助
用 namedtuple 構(gòu)建的類的實(shí)例所消耗的內(nèi)存跟元組是一樣的饰序,因?yàn)樽侄蚊急淮嬖趯?duì)應(yīng)的類里面速缆。這個(gè)實(shí)例跟普通的對(duì)象實(shí)例比起來也要小一些,因?yàn)?Python 不會(huì)用 __dict__ 來存放這些實(shí)例的屬性禁荸。
具名元組顧名思義可以理解為有具體名字的元組右蒲,有點(diǎn)類似字典,不過具名元組的值是不能改變的赶熟。
已經(jīng)有了普通元組瑰妄,為什么還需要具名元組?
因?yàn)槠胀ㄔM映砖,無法為元組內(nèi)部的數(shù)據(jù)起名字间坐,經(jīng)常會(huì)疑惑一個(gè)元組到底要表達(dá)什么意思。而具名元組邑退,則可以通過字段名訪問
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22) # 用位置參數(shù)或關(guān)鍵字實(shí)例化
>>> p[0] + p[1] # 和普通元組一樣可以使用索引
33
>>> x, y = p
>>> x, y
(11, 22)
>>> p.x + p.y
33
>>> d = p._asdict() # 具名元組轉(zhuǎn)換成字典
>>> d['x']
11
>>> Point(**d) # 字典轉(zhuǎn)換成具名元組
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
展示了具名元組來記錄一個(gè)城市的信息的實(shí)例
>>> from collections import namedtuple
# 創(chuàng)建一個(gè)具名元組需要兩個(gè)參數(shù)竹宋,一個(gè)是類名,另一個(gè)是類的各個(gè)字段的名字
>>> City = namedtuple('City', 'name country population coordinates')
# 存放在對(duì)應(yīng)字段里的數(shù)據(jù)要以一串參數(shù)的形式傳入到構(gòu)造函數(shù)中
>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
>>> tokyo
City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722,139.691667))
>>> tokyo.population # 你可以通過字段名或者位置來獲取一個(gè)字段的信息
36.933
>>> tokyo.coordinates
(35.689722, 139.691667)
>>> tokyo[1]
'JP'
除了從普通元組那里繼承來的屬性之外地技,具名元組還有一些自己專有的屬性蜈七。下面展示其中幾個(gè)最常用的方法:_fields
類屬性、類方法_make(iterable)
和實(shí)例方法_asdict()
乓土。
下面我們一個(gè)個(gè)講解
1. 具名元組的_fields
方法:
>>> City = namedtuple('City', 'name country population coordinates')
>>> tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
>>> tokyo
City(name='Tokyo', country='JP', population=36.933, coordinates=(35.689722, 139.691667))
>>> City._fields # _fields相當(dāng)于打印元組名字
('name', 'country', 'population', 'coordinates')
2. 具名元組的_make(iterable)
方法:
# 接上個(gè)實(shí)驗(yàn)
>>> LatLong = namedtuple('LatLong', 'lat long')
>>> delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
>>> City._make(delhi_data)
City(name='Delhi NCR', country='IN', population=21.935, coordinates=LatLong(lat=28.613889, long=77.208889))
3. 具名元組的_asdict()
方法:
# 接上個(gè)實(shí)驗(yàn)
>>> delhi = City._make(delhi_data)
>>> delhi._asdict() #獲得一個(gè)有序字典
{'name': 'Delhi NCR', 'country': 'IN', 'population': 21.935, 'coordinates': LatLong(lat=28.613889, long=77.208889)}
# 將上面的字典格式化輸出
>>> for key, value in delhi._asdict().items():
print(key + ':', value)
name: Delhi NCR
country: IN
population: 21.935
coordinates: LatLong(lat=28.613889, long=77.208889)
_asdict() 把具名元組以 collections.OrderedDict
的形式返回宪潮,我們可以利用它來把元組里的信息友好地呈現(xiàn)出來。
collections.OrderedDict:返回一個(gè)有序的字典子類實(shí)例趣苏,具體可以參考官方文檔:collections.OrderedDict