Python 中的 Namedtuple
NamedTuple 是 collections 模組下的另一個類。與字典型別物件一樣,它包含對映到某個值的鍵。這種情況,我們可以使用鍵和索引來訪問元素。
首先使用它,我們需要匯入 collections 標準庫模組。
import collections
在這一節中,我們將看到 NamedTuple 類的部分函式。
NamedTuple 的訪問方法
透過 NamedTuple,我們可以使用索引、鍵和 getattr() 方法來訪問值。NamedTuple 的屬性值是有序的。因此我們可以使用索引來訪問它們。
NamedTuple 將欄位名作為 attributes。因此使用 getattr() 可以從該 attribute 中獲取資料。
示例程式碼
import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#Add two employees
e1 = Employee('Asim', 'Delhi', '25000')
e2 = Employee('Bibhas', 'Kolkata', '30000')
#Access the elements using index
print('The name and salary of e1: ' + e1[0] + ' and ' + e1[2])
#Access the elements using attribute name
print('The name and salary of e2: ' + e2.name + ' and ' + e2.salary)
#Access the elements using getattr()
print('The City of e1 and e2: ' + getattr(e1, 'city') + ' and ' + getattr(e2, 'city'))
輸出
The name and salary of e1: Asim and 25000 The name and salary of e2: Bibhas and 30000 The City of e1 and e2: Delhi and Kolkata
NamedTuple 的轉換過程
有些方法可以將其他集合轉換成 NamedTuple。_make() 方法可以用來將 list、tuple 等可迭代物件轉換成 NamedTuple 物件。
我們還可以將字典型別物件轉換成 NamedTuple 物件。對於此轉換,我們需要 ** 運算子。
NamedTuple 可以返回使用鍵作為 OrderedDict 型別物件的的值。為了使它成為 OrderedDict,我們必須使用 _asdict() 方法。
示例程式碼
import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#List of values to Employee
my_list = ['Asim', 'Delhi', '25000']
e1 = Employee._make(my_list)
print(e1)
#Dict to convert Employee
my_dict = {'name':'Bibhas', 'city' : 'Kolkata', 'salary' : '30000'}
e2 = Employee(**my_dict)
print(e2)
#Show the named tuple as dictionary
emp_dict = e1._asdict()
print(emp_dict)
輸出
Employee(name='Asim', city='Delhi', salary='25000')
Employee(name='Bibhas', city='Kolkata', salary='30000')
OrderedDict([('name', 'Asim'), ('city', 'Delhi'), ('salary', '25000')])
關於 NamedTuple 的附加操作
還有一些其它方法,如 _fields() 和 _replace()。使用 _fields() 方法我們可以檢查什麼是 NamedTuple 的不同欄位。_replace() 方法用於用另一個值代替某個值。
示例程式碼
import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#Add an employees
e1 = Employee('Asim', 'Delhi', '25000')
print(e1)
print('The fields of Employee: ' + str(e1._fields))
#replace the city of employee e1
e1 = e1._replace(city='Mumbai')
print(e1)
輸出
Employee(name='Asim', city='Delhi', salary='25000')
The fields of Employee: ('name', 'city', 'salary')
Employee(name='Asim', city='Mumbai', salary='25000')
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP