Skip to main content
 首页 » 编程设计

python之遍历包含字典的嵌套列表

2024年11月01日9daizhj

嗨,我如何循环遍历下面的 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在e中则打印字典

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}]] 

请您参考如下方法:

您需要从 e 列表和 flatten 创建一个映射(字典) n list of list of tuples into list of tuples:

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