2013-10-09 58 views
0

我的數據是這樣的:兩個列表與一些不同的密鑰字典,如何找到交集?

buffer = [{"siteid": 1 , "distance": 2, "codes": "1|b|c", "urv": "545"}, {"siteid": 2 , "distance": 2, "codes": "1|b|c", "urv": "55"}, {"siteid": 2 , "distance": 2, "codes": "1|b|c", "urv": "55"}, {"siteid": 3 , "distance": 2, "codes": "1|b|c", "urv": "546"}] 
layer = [{"siteid": 2 }, {"siteid": 4 }, {"siteid": 3 }] 

我希望能夠返回所有緩衝區列表的成員,其中SITEID是一樣的。

其結果將是:

[{"siteid": 2 , "distance": 2, "codes": "1|b|c", "urv": "55"}, {"siteid": 2 , "distance": 2, "codes": "1|b|c", "urv": "55"}, {"siteid": 3 , "distance": 2, "codes": "1|b|c", "urv": "546"}] 

TIA, 克里斯

+3

同樣的是什麼?什麼是圖層列表? –

+0

@AidanKane,我更新了問題。 – CLJ

回答

1

這樣的事情?

buffer = [{"siteid": 1 , "distance": 2, "codes": "1|b|c", "urv": "545"}, {"siteid": 2 , "distance": 2, "codes": "1|b|c", "urv": "55"}, {"siteid": 2 , "distance": 2, "codes": "1|b|c", "urv": "55"}, {"siteid": 3 , "distance": 2, "codes": "1|b|c", "urv": "546"}] 
layer = [{"siteid": 2 }, {"siteid": 4 }, {"siteid": 3 }] 
ids = [l['siteid'] for l in layer] 
print [b for b in buffer if b['siteid'] in ids] 
+0

首選列表解析到'filter':'[x for x in buffer if x ['siteid'] in ids]' –

+0

夠公平 - 不確定爲什麼我在這裏使用過濾器 - 我通常使用列表解析。將更新我的答案。 –

+0

謝謝你的回答! – CLJ

1

我不知道,能做到這一點任何內置的,但你可以嘗試編寫自己的功能找到的交集你的兩個詞:

def find_intersection(buffer, layer): 
    siteids = [a['siteid'] for a in layer] 
    return [item for item in buffer if item['siteid'] in siteids] 
+0

謝謝你的回答! – CLJ

1
intersection = set(x['sideid'] for x in buffer) & set(x['siteid'] for x in layer) 
return [x for x in buffer if x['sideid'] in intersection] 
+0

謝謝你的回答! – CLJ

相關問題