2014-03-31 106 views
2

嗨如何循環遍歷下面的n,並獲取e中的字典元素,如果元素匹配。循環遍歷包含字典的嵌套列表

e = [(1001, 7005, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}), 
    (1002, 8259, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}), (1001, 14007, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9})] 

n = [[(1001, 7005), (3275, 8925)], [(1598, 6009), (1001, 14007)]] 

即比較n和如果n是在電子打印字典

b = [] 
for d in n: 
    for items in d: 
     print b 

結果應該是

output = [[{'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}],[{'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}]] 

回答

1

您需要創建從e表的映射(字典) flattenn列表元組的名單到元組的列表:

e = [(1001, 7005, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}), 
    (1002, 8259, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9}), 
    (1001, 14007, {'length': 0.35, 'modes': 'cw', 'type': '99', 'lanes': 9})] 

n = [[(1001, 7005),(3275, 8925)], [(1598,6009),(1001,14007)]] 

d = {(item[0], item[1]): item[2] for item in e} 
n = [item for sublist in n for item in sublist] 

print [d[item] for item in n if item in d] 

個打印:

[{'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}, 
{'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}] 
+0

感謝,但輸出應該是單獨的字典作爲@thefourtheye有它 – user3481663

+0

@ user3481663不一個問題,檢查更新。 – alecxe

1

您可以將e列表轉換爲一個字典,以字典的理解,像這樣

f = {(v1, v2):v3 for v1, v2, v3 in e} 

然後,我們可以拼合n並檢查每個元素是否在f之內。如果它是存在的,那麼我們可以從f得到相應的價值,這樣

from itertools import chain 
print [f[item] for item in chain.from_iterable(n) if item in f] 

輸出

[{'lanes': 9, 'length': 0.35, 'modes': 'cw', 'type': '99'}, 
{'lanes': 9, 'length': 0.35, 'modes': 'cw', 'type': '99'}] 
0

您可以使用列表理解:

[e1[2] for e1 in e for n1 in n for n2 in n1 if (e1[0]==n2[0] and e1[1]==n2[1])] 

輸出:

[{'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}, 
{'lanes': 9, 'length': 0.35, 'type': '99', 'modes': 'cw'}] 
+0

謝謝,但是輸出應該是字典本身,因爲@thefourtheye有它 – user3481663

+0

好的..你可以添加e1 [2]而不是e1。我將編輯我的答案.. – user3

+0

但奇怪的是你的代碼的輸出是在我的機器上的一個空列表,它可能是由於不同的python版本?我使用python 2.7 – user3481663