0

数据来源是带有 2 个连接的 Mysql 查询。查询返回一个值列表,如下所示:

title   start   additive

title1  5885    NULL
title2  8829    add1
title2  8829    add2
title3  3697    NULL

如您所见,当有超过 1 个添加剂时,JOIN 查询会创建标题/开始的重复项。标题应该是唯一的,并且应该将添加剂添加到列表中。

我的最终目标是以以下格式输出 json 数据:

[
    {
        title: 'some-title',
        start: '584487',
        additives: [ 'add1': 58, 'add2': 98 ]
    },
    {
        etc...
    },
    {
        etc...
    }
]

我现在正在做的是创建一个列表并用字典对象填充它。但是我得到重复。如何将值添加到列表中,以便获得唯一标题和任意数量添加剂的列表?

从我对 python 的有限理解来看,似乎没有一种直接的方法来实现这一点。

在 PHP 中,使用关联数组会很简单:

foreach ...
   stages[stageTitle]['start'] = '8585';
   stages[stageTitle]['additives'] = [];
   //and to add to additives on title duplicate
   stages[stageTitle]['additives'].push(new Array('additiveTitle' => '58'))

我的代码:

# sql query here...

    data = self.cursor.fetchall()

            stages = []
            for stage in data:
                title= stage[0]
                start = stage[1]
                additive = stage[3]

             # I am stuck from here on.
             # I cant use keys for list as they have to be numeric
             # and I can't append to dict object
             # tulpe is immutable so no good here either
4

1 回答 1

0

由于它是titlestart的独特组合,因此您可以使用这一事实,将这两者的元组作为 a 的键defaultdict

from collections import defaultdict

data = [
    ['title1', '5885', '-', 'NULL', ...],
    ['title2', '8829', '-', 'add1', ...],
    ['title2', '8829', '-', 'add2', ...],
    ['title3', '3697', '-', 'NULL', ...],
]

stages = defaultdict(list)
for stage in data:
    title, start, additive = stage[0], stage[1], stage[3]
    stages[(title, start)].append(additive)

>>> from pprint import pprint
>>> pprint(stages)
{('title1', '5885'): ['NULL'],
 ('title2', '8829'): ['add1', 'add2'],
 ('title3', '3697'): ['NULL']}
>>> 
于 2013-07-31T19:59:09.383 回答