我从数据库返回的记录如下:
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
我正试图把他们列入名单:
总资产:
^{pr2}$num_类:
[{"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)
太好了,这让我得到了我的全部附件列表,但是我做了一个额外的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执行multiple操作呢?在
我希望这是清楚的,但很高兴提供更多的必要信息。在
相关问题 更多 >
编程相关推荐