[英]Merging two lists of tuples of different size into a list of dictionaries
Now I have two lists of tuples of different size like this:现在我有两个不同大小的元组列表,如下所示:
a = [('NC', 0, 'Eyes'),('NC', 3, 'organs'),('NC', 19, 'neurons'),...]
b = [(0, 'Hypernym', 3),(19, 'Holonym', 0),...]
The common values from the above lists is the int number, and the expected result should look like:上面列表中的常见值是 int 数,预期结果应如下所示:
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'},
...]
I have converted the above two lists into dictionaries and tried nested loop but failed to get this output.我已将上述两个列表转换为字典并尝试嵌套循环,但未能获得此输出。 Can somebody kindly help me out?有人可以帮助我吗?
I managed to get this one working.我设法让这个工作。 Let me know if there are any other specifics that need fixing.让我知道是否还有其他需要修复的细节。
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)
I hope this is what you were looking for.我希望这就是你要找的。 There are many other ways to do this, but given your description of the problem, this should do.有很多其他方法可以做到这一点,但鉴于您对问题的描述,应该这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.