簡體   English   中英

根據任意字段查找字典列表的交集

[英]Finding the intersection of a list of dictionaries based on an arbitrary field

說我有一個字典l1l2的列表。 每個字典都包含相同格式的字典。 我想根據字典的某個字段找到l1l2的交集。

例如,讓

l1 = [{"key":1, "key2":2}, {"key":1, "key2":0}],
l2 = [{"key":0, "key2":2}]. 

我想根據“ key2”將它們相交。 因此, l1.intersect(l2) = 2

如果我沒有記錯的話,我可以按照以下步驟進行操作,它的復雜度為O(len(l1)+ len(l2))。

d = defaultdict(bool)
for e in l2:
    d[e['key2']] = True
intersection=set()
for e in l1:
    if d[e['key2']]:
        intersection.add(e['key2])

我想知道的是,是否存在更好的解決方案,或者我的解決方案是否已經最優。

您可以使用set comprehensions使它緊湊。 例如,

l1 = [{"key":1, "key2":2}, {"key":3, "key2":4}, {"key":5, "key2":6}, {"key":7, "key2":8}]
l2 = [{"key":0, "key2":2}, {"key":1, "key2":3}, {"key":2, "key2":4}]

key = "key2"
values = {d[key] for d in l1} & {d[key] for d in l2}
print(values)

輸出

{2, 4}

您可以通過在函數中進行設置理解來使代碼更具可讀性,盡管函數調用會使代碼在微觀上變慢。

def key_set(seq, key):
    return {d[key] for d in seq}

values = key_set(l1, key) & key_set(l2, key)

可以普遍使用此技術來處理任意數量的列表。

all_lists = (l1, l2)
key = "key2"
values = set.intersection(*({d[key] for d in seq} for seq in all_lists))

暫無
暫無

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

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