我从数据库返回的记录如下所示:
region month_taken total_att num_classes
Colorado 2013-01-01 00:00:00.000 78485 4648
Colorado 2013-02-01 00:00:00.000 71769 4162
Midwest 2013-01-01 00:00:00.000 110508 7101
Midwest 2013-02-01 00:00:00.000 103545 6410
我试图让他们进入列表:
Total_att:
[{"data": [78485, 71769], "name": "Colorado"}, {"data": [110508, 103545], "name": "Midwest"}]
num_classes:
[{"data": [4648, 4162], "name": "Colorado"}, {"data": [7101, 6410], "name": "Midwest"}]
我发现了itertools.groupby,它可以完成我想要的工作,但是我在使用多个值列表时遇到困难(因为没有更好的术语)。
totalResults = []
for key, location in groupby(rows, lambda k: k[0]):
totalRow = dict()
totalRow['name'] = key
totalRow['data'] = [x[2] for x in location]
totalResults.append(totalRow)
太棒了,这让我得到了我的total_att列表,但后来又做了一个额外的groupby循环来创建" num_classes"列表,这看起来很荒谬。我在文档中看到了这一点,但老实说,如果我将其转换为列表,我不太确定它的含义或如何处理我的问题:
The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby() object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list:
那么,我如何创建我的列表而不用为groupby中的键,位置(行,lambda k:k [0])做多个:?
我希望这很清楚,但我很乐意在必要时提供更多信息。
答案 0 :(得分:2)
totalResults = []
totalClasses = []
for key, location in groupby(rows, lambda k: k[0]):
location = list(location)
totalResults.append(dict(name=key, data=[x[2] for x in location]))
totalClasses.append(dict(name=key, data=[x[3] for x in location]))