如何基于相同的值对数组进行分组

时间:2017-05-17 06:39:44

标签: python arrays django sparql ontology

请与python中的数组混淆。我想基于相同的值对数组进行分组。

代码:

enter image description here

id_disease = ['penyakit_tepung','hawar_daun']
for id_disease in id_disease:
    qres = acacia.query( 
        """
        PREFIX tst: <http://www.semanticweb.org/aalviian/ontologies/2017/1/untitled-ontology-10#>
        SELECT ?disease ?patogen
        WHERE { 
            ?disease tst:caused_by ?patogen . 
            FILTER regex(str(?disease), "%s") .
        } """ % id_disease )

    for row in qres:
        for r in row:
            print(r.replace('http://www.semanticweb.org/aalviian/ontologies/2017/1/untitled-ontology-10#',''))
        print("\n")

输出:

penyakit_tepung
spaerotheca_sp

penyakit_tepung
oidium_sp


penyakit_tepung
erysiphe_sp


hawar_daun
cylindrocladium_sp


hawar_daun
kirramyces_sp


hawar_daun
phaeophleopspora_sp

预期数组:

[['spaeerotheca_sp','oidium_sp','erysiphe_sp'].['cylindrocladium_sp','kirramyces_sp','phaeophleopspora_sp']]

如果你知道如何获得它,请帮助我。

2 个答案:

答案 0 :(得分:0)

应该是

listoflists = []

for row in qres:
    a_list = []

        for r in row:
           data = r.replace('http://www.semanticweb.org/aalviian/ontologies/2017/1/untitled-ontology-10#','')
           a_list.append(data)

    listoflists.append(a_list)

print listoflists

答案 1 :(得分:0)

我采用的一般方法是创建一个将每个键映射到列表的字典。

说出你的输入列表如下:

[
 ['a', 'A'], ['a', 'B'], 
 ['b', 'D'], ['b', 'E'],
 ['a', 'C']
]

我要做的是:

map = {}
for item in input:
    key, value = item  # destructuring assignment
    if not key in map: map[key] = []  # initialize a spot for the key if not seen before
    map[key].append(value)

现在我们应该有一个如下所示的地图:

{'a': ['A', 'B', 'C'], 'b': ['D', 'E']}