namedtuple

date
Jun 19, 2021
slug
46
status
Published
tags
Python
summary
type
Post

python神级数据结构namedtuple

from collections import namedtuple
以前就知道有这个东西,也知道如何使用,但是没觉得有什么实际用处. 上次看框架源码,无意间看到这个,发现非常好用.
namedtuple实际上是灵活的创建了一个对象而不是tuple. tuple的功能主要是为了赋值用.直接举例子

基本用法

>>> # Basic example
>>> Point = namedtuple('Point', ['x', 'y'])
>>> p = Point(11, y=22)
# instantiate with positional or keyword arguments# 
>>> p = Point(11, 22)
>>> p[0] + p[1]             
# indexable like the plain tuple (11, 22)33
>>> x, y = p                
# unpack like a regular tuple
>>> x, y(11, 22)
>>> p.x + p.y               
# fields also accessible by name33
>>> p                       
# readable __repr__ with a name=value stylePoint(x=11, y=22)

经典用法

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import sqlite3conn = 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)
classmethodsomenamedtuple._make(iterable)
>>> t = [11, 22]
>>> Point._make(t)
Point(x=11, y=22)

神级用法

somenamedtuple._asdict() 完美解决,类似sqlalchemy这种,无法返回dict问题.
>>> p = Point(x=11, y=22)
>>> p._asdict(){'x': 11, 'y': 22}
例子
EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')

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._asdict())

© chaleaoch 2021