Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在包含字典的嵌套列表中循环_Python_Loops_Dictionary - Fatal编程技术网

Python 在包含字典的嵌套列表中循环

Python 在包含字典的嵌套列表中循环,python,loops,dictionary,Python,Loops,Dictionary,您好,我如何在下面的n中循环,如果元素匹配,如何在e中获得dictionary元素 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'

您好,我如何在下面的n中循环,如果元素匹配,如何在e中获得dictionary元素

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
列表转换为具有字典理解功能的字典,如下所示

f = {(v1, v2):v3 for v1, v2, v3 in e}
from itertools import chain
print [f[item] for item in chain.from_iterable(n) if item in f]
然后,我们可以展平
n
并检查每个元素是否在
f
中。如果它在那里,那么我们可以从
f
中得到对应的值,如下所示

f = {(v1, v2):v3 for v1, v2, v3 in e}
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'}]

您需要从元组列表的
e
列表和
n
列表创建映射(字典)到元组列表:

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

您可以使用列表理解:

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

谢谢,但是输出应该是单独的字典,因为@thefourtheye有它,但是奇怪的是,您的代码输出在我的机器上是一个空列表,这可能是不同python版本的结果吗?我使用Python2.7谢谢,但是输出应该是单独的字典,因为@thefourtheye有它