将两个大小不同的元组列表合并到一个字典列表中

2024-09-29 23:28:14 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我有两个不同大小的元组列表,如下所示:

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'},
    ...]

我已将上述两个列表转换为字典,并尝试嵌套循环,但未能获得此输出。谁能帮我一下吗


Tags: 列表字典type整数result元组嵌套循环nc
1条回答
网友
1楼 · 发布于 2024-09-29 23:28:14

我设法让这个工作。如果有任何其他细节需要解决,请告诉我

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)

我希望这就是你想要的。 有很多其他的方法可以做到这一点,但是根据您对问题的描述,这应该可以做到

相关问题 更多 >

    热门问题