如何基于相同的值对数组进行分组 [英] How to group array based on the same values

查看:201
本文介绍了如何基于相同的值对数组进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请与python中的数组混淆.我想根据相同的值对数组进行分组.

Please, confused with array in python. I want to group array based on the same values.

代码:

在此处输入图片描述

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']]

请帮助我,如果您知道如何获得它.

Please, help me if you know how step to get it.

推荐答案

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

The general approach I take is to create a dictionary mapping each key to a list.

说您的输入列表如下:

[
 ['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)

现在我们应该有一张看起来像这样的地图:

Now we should have a map that looks like this:

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

这篇关于如何基于相同的值对数组进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆