Python中collections.namedtuple用法
namedtuple可用于创建一个命名元组类
官方文档:collections --- 容器数据类型 — Python 3.12.0 文档
简单示例:
from collections import namedtuple
# 创建一个命名元组类
Person = namedtuple('Person', 'name age gender')
# 使用 _make() 方法将序列转换为命名元组
person_data = ['John', '25', 'Male']
person = Person._make(person_data)
# 输出命名元组的属性值
print(person.name) # John
print(person.age) # 25
print(person.gender) # Male
上面提示到_make()方法,该方法用于将一个可迭代对象转换为命名元组,常用于将csv sqlite3模块返回的数据转化为命名元组:
# 创建一个命名元组类
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import csv
# 将获取到的csv数据,转化为命名元组(n个 EmployeeRecord 对象组成)
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
print(emp.name, emp.title)
import sqlite3
conn = sqlite3.connect('/companydata')
cursor = conn.cursor()
cursor.execute('SELECT name, age, title, department, paygrade FROM employees')
for emp in map(EmployeeRecord._make, cursor.fetchall()):
print(emp.name, emp.title)