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 name
33
>>> p # readable __repr__ with a name=value style
Point(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.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())