namedtuple映射名称到序列元素

In [1]: from collections import namedtuple

In [2]: dt = namedtuple('s', ['name', 'job'])

In [3]: ret = dt('hys', 'coder')

In [4]: ret.name
Out[4]: 'hys'

In [5]: ret.job
Out[5]: 'coder'

将cursor.fetchall()返回的元组转换成可以通过名称来访问的元组

In [1]: from collections import namedtuple
...:
...: def tuple_to_namedtuple(t, name_list):
...:     ret_list = []
...:     s_namedtuple = namedtuple('s_namedtuple',name_list)
...:     for item in t:
...:         ret_list.append(s_namedtuple._make(item))
...:         return ret_list
...:

In [2]: import sqlite3

In [3]: conn = sqlite3.connect('tst.sqlite3')

In [4]: cursor = conn.cursor()

In [5]: cursor.execute('select * from t')
Out[5]: <sqlite3.Cursor at 0x7f48b8079500>

In [6]: r = tuple_to_namedtuple(cursor.fetchall(),['id', 'name', 'value'])

In [7]: r
Out[7]:
[s_namedtuple(id=1, name='hys', value='a'),
s_namedtuple(id=2, name='huang', value='b')]

通过map实现,简洁许多

In [10]: def tuple_to_dict(seq, name_list):
...:         s_namedtuple = namedtuple('s_namedtuple',name_list)
...:         return map(s_namedtuple._make, seq)
...:

In [12]: ret = tuple_to_dict(cursor.fetchall(),['id','name','value'])

In [13]: ret
Out[13]: <map at 0x7f48b2fa2a90>

In [14]: for elt in ret:
...:         print(elt)
...:
s_namedtuple(id=1, name='hys', value='a')
s_namedtuple(id=2, name='huang', value='b')