将两个不同大小的元组列表合并到字典列表中
Merging two lists of tuples of different size into a list of dictionaries
现在我有两个不同大小的元组列表,如下所示:
a = [('NC', 0, 'Eyes'),('NC', 3, 'organs'),('NC', 19, 'neurons'),...]
b = [(0, 'Hypernym', 3),(19, 'Holonym', 0),...]
以上列表中的常见值是整数,预期结果应如下所示:
result = [
{'s_type':'NC', 's':'Eyes', 'predicate':'Hypernym', 'o_type':'NC', 'o':'organs'},
{'s_type':'NC', 's':'neurons', 'predicate':'Holonym', 'o_type':'NC', 'o':'Eyes'},
...]
我已将上述两个列表转换为字典并尝试嵌套循环但未能获得此输出。有人可以帮助我吗?
我设法让它工作了。让我知道是否还有其他需要修复的细节。
a = [('NC', 0, 'Eyes'), ('NC', 3, 'organs'), ('NC', 19, 'neurons')]
b = [(0, 'Hypernym', 3), (19, 'Holonym', 0)]
result = []
for s_type, common, s in a:
related = list(filter(lambda x: x[0] == common, b))
for o_type, predicate, next in related:
next_related = list(filter(lambda x: x[1] == next, a))
for s_type, _, organ in next_related:
result.append({'s_type': s_type, 's': s,
'predicate': predicate, 'o_type': o_type, 'o': organ})
print(result)
希望这就是您要找的。
有很多其他方法可以做到这一点,但根据您对问题的描述,应该这样做。
现在我有两个不同大小的元组列表,如下所示:
a = [('NC', 0, 'Eyes'),('NC', 3, 'organs'),('NC', 19, 'neurons'),...]
b = [(0, 'Hypernym', 3),(19, 'Holonym', 0),...]
以上列表中的常见值是整数,预期结果应如下所示:
result = [
{'s_type':'NC', 's':'Eyes', 'predicate':'Hypernym', 'o_type':'NC', 'o':'organs'},
{'s_type':'NC', 's':'neurons', 'predicate':'Holonym', 'o_type':'NC', 'o':'Eyes'},
...]
我已将上述两个列表转换为字典并尝试嵌套循环但未能获得此输出。有人可以帮助我吗?
我设法让它工作了。让我知道是否还有其他需要修复的细节。
a = [('NC', 0, 'Eyes'), ('NC', 3, 'organs'), ('NC', 19, 'neurons')]
b = [(0, 'Hypernym', 3), (19, 'Holonym', 0)]
result = []
for s_type, common, s in a:
related = list(filter(lambda x: x[0] == common, b))
for o_type, predicate, next in related:
next_related = list(filter(lambda x: x[1] == next, a))
for s_type, _, organ in next_related:
result.append({'s_type': s_type, 's': s,
'predicate': predicate, 'o_type': o_type, 'o': organ})
print(result)
希望这就是您要找的。 有很多其他方法可以做到这一点,但根据您对问题的描述,应该这样做。