1

我有从如下所示的数据库返回的记录:

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"}]

类数:

[{"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(rows, lambda k: k[0]): 中为 key 和 location 执行多个操作?

我希望这很清楚,但我很乐意在必要时提供更多信息。

4

1 回答 1

4
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]))
于 2013-03-16T13:54:35.830 回答