我是Python和SQLite的新手,我正在努力学习 如何转换存储在关系中的列表(考试分数) 数据库进入python列表[子列表]。鉴于这些信息 下面,我该怎样才能做到这一点。
Exam(id, t_date, name)
Result(id, exam_id, score)
INSERT INTO Exam VALUES(1, '2014-01-31', 'Sql Fundamentals')
INSERT INTO Result VALUES(1, 1, 87)
INSERT INTO Result VALUES(2, 1, 65)
INSERT INTO Result VALUES(3, 1, 98)
SELECT
E.id, E.t_date, E.[name], R.score
FROM
Exam AS E INNER JOIN Result AS R
ON
E.ID = R.exam_id
1, '2014-01-31', 'Sql Fundamentals', 87
1, '2014-01-31', 'Sql Fundamentals', 65
1, '2014-01-31', 'Sql Fundamentals', 98
[1, '2014-01-31', 'Sql Fundamentals', [87, 65, 98]]
答案 0 :(得分:0)
SQLite将查询作为元组列表返回。在这种情况下,您可以这样做:
>>> test = [(1, '2014-01-31', 'Sql Fundamentals', 87), (1, '2014-01-31', 'Sql Fundamentals', 65), (1, '2014-01-31', 'Sql Fundamentals', 98)]
>>> from collections import defaultdict
>>> final = defaultdict(list)
>>> for elem in test:
final[elem[:3]].append(elem[-1])
>>> final
defaultdict(<type 'list'>, {(1, '2014-01-31', 'Sql Fundamentals'): [87, 65, 98]})
>>> final[(1, '2014-01-31', 'Sql Fundamentals')]
[87, 65, 98]