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'))
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
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')
广告