簡體   English   中英

將兩個不同大小的元組列表合並到一個字典列表中

[英]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),...]

上面列表中的常見值是 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'},
    ...]

我已將上述兩個列表轉換為字典並嘗試嵌套循環,但未能獲得此輸出。 有人可以幫助我嗎?

我設法讓這個工作。 讓我知道是否還有其他需要修復的細節。

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)

我希望這就是你要找的。 有很多其他方法可以做到這一點,但鑒於您對問題的描述,應該這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM