问题
Please, confused with array in python. I want to group array based on the same values.
Code:
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")
Output:
penyakit_tepung
spaerotheca_sp
penyakit_tepung
oidium_sp
penyakit_tepung
erysiphe_sp
hawar_daun
cylindrocladium_sp
hawar_daun
kirramyces_sp
hawar_daun
phaeophleopspora_sp
Expected Array :
[['spaeerotheca_sp','oidium_sp','erysiphe_sp'].['cylindrocladium_sp','kirramyces_sp','phaeophleopspora_sp']]
Please, help me if you know how step to get it.
回答1:
It should be
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
回答2:
The general approach I take is to create a dictionary mapping each key to a list.
Say your input list looks like this:
[
['a', 'A'], ['a', 'B'],
['b', 'D'], ['b', 'E'],
['a', 'C']
]
What I would do is:
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']}
来源:https://stackoverflow.com/questions/44017347/how-to-group-array-based-on-the-same-values