如何解码嵌套到字典中的列表理解?

时间:2018-03-14 13:12:32

标签: python list-comprehension

我无法理解以下代码段:

_dict = {}
_dict['ut'] = {pos: [unit for unit in all_merge if pos in unit] for pos in mxn}

其中,all_merge和mxn是列表。

我想展开上面代码的理解,并希望得到如下格式的结果:

for x in y:
   for a in b:
       if u in v:
           #do something

请帮帮我。

2 个答案:

答案 0 :(得分:2)

一步一步地分解:

elementPosition 0

首先显示外部for循环:

_dict = {}
_dict['ut'] = {pos: [unit for unit in all_merge if pos in unit] for pos in mxn}

然后打破列表理解:

for pos in mxn:
    _dict{pos :[unit for unit in all_merge if pos in unit]}

然后将它们组合在一起,你可以将temp_dict替换为其他东西,但只是一个更明确的例子,我想发生了什么:

temp_list = []
for unit in all_merge:
    if pos in unit:
        temp_list.append(unit)

答案 1 :(得分:0)

我想是这样的:

ut = {}

for pos in mxn:
    val = []
    for unit in all_merge:
        if pos in unit:
            val.append(unit)
    ut[pos] = val

_dict['ut'] = ut

你能提供一些样本输入和输出吗?