【问题标题】:How can I decode list comprehension nested into dictionary?如何解码嵌套到字典中的列表理解?
【发布时间】:2018-08-23 00:55:37
【问题描述】:

我无法理解以下代码 sn-p:

_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

请帮帮我。

【问题讨论】:

  • 如果您了解输出和输入,为什么不自己尝试循环方法呢?否则为什么要展开有效的理解?
  • 为了清楚起见,也许添加一些示例数据?

标签: python list-comprehension


【解决方案1】:

我是这样想的:

ut = {}

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

_dict['ut'] = ut

你能提供一些示例输入和输出吗?

【讨论】:

  • 哎呀这不起作用。 val 初始化太深。
  • @Jean-FrançoisFabre 你的意思是它应该被编辑?
  • 那更好:)
【解决方案2】:

逐步分解:

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

先引出外层for循环:

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

然后打破列表理解:

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

然后将它们组合在一起,您可以将 temp_dict 替换为其他东西,但我猜这只是一个更清晰的例子:

_dict = {}
temp_dict = {}
for pos in mxn:
    temp_list = []
    for unit in all_merge:
        if pos in unit:
            temp_list.append(unit)
    temp_dict[pos] = temp_list
_dict['ut'] = temp_dict

【讨论】:

    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 2013-11-15
    • 2021-12-22
    • 1970-01-01
    • 2011-02-19
    • 2020-01-08
    • 2017-11-27
    • 1970-01-01
    相关资源
    最近更新 更多