如何以正确的顺序在Python中构造嵌套字典理解? [英] How to construct nested dictionary comprehension in Python with correct ordering?

查看:96
本文介绍了如何以正确的顺序在Python中构造嵌套字典理解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图缩短此问题的代码我遇到了这个问题。

I was trying to shorten the code for this problem when I encountered the problem.

基本上,我正在尝试嵌套字典理解&尝试失败。
这是我尝试的方法。

Basically, I was trying a nested dictionary comprehension & was unsuccessful in the attempt. Here is what I tried.

dict2 = {key:value for key, value in line.split(":")
                   for line in ["1:One", "2:Two", "4:Four"]}
print dict2

运行此命令时,它会给我

When I run this, it gives me

NameError: name 'line' is not defined

而且,当我反转语句

dict2 = {key:value for line in ["1:One", "2:Two", "4:Four"]
                   for key, value in line.split(":")}
print dict2

其结果是

ValueError: need more than 1 value to unpack

我需要有关字典的嵌套结构的帮助(或 list )理解。

I need help on the nesting structure of dictionary (or list) comprehension. An example would be help a lot.

推荐答案

请注意,没有dict理解的方法还有更好的方法。见下文。我将首先用您的方法解决问题。

Note that there is a better way of doing this without a dict comprehension; see below. I’ll first address the issues with your approach.

您需要使用嵌套顺序进行理解。以嵌套常规循环时的顺序列出循环。

You need to use nesting order in comprehensions. List your loops in the same order they would be in when nesting a regular loop.

line.split() expression返回由两个项目组成的序列,但是每个项目都是 not 键和值的元组;相反,只有一个 one 元素被迭代。将拆分包裹在一个元组中,这样就产生了一个(键,值)项的序列,将两个结果分配给两个项:

The line.split() expression returns a sequence of two items, but each of those items is not a tuple of a key and a value; instead there is only ever one element being iterated over. Wrap the split in a tuple so you have a 'sequence' of (key, value) items being yielded to assign the two results to two items:

dict2 = {key:value for line in ["1:One", "2:Two", "4:Four"]
                   for key, value in (line.split(":"),)}

的:

dict2 = {}
for line in ["1:One", "2:Two", "4:Four"]:
    for key, value in (line.split(":"),):
        dict2[key] = value

仅由于无法执行嵌套循环而需要嵌套循环:

where the nested loop is only needed because you cannot do:

dict2 = {}
for line in ["1:One", "2:Two", "4:Four"]:
    key, value = line.split(":")
    dict2[key] = value

但是,在这种情况下,不是字典理解,则应使用 dict()构造函数。它想要两个元素的序列,从而简化了整个操作:

However, in this case, instead of a dictionary comprehension, you should use the dict() constructor. It wants two-element sequences, simplifying the whole operation:

dict2 = dict(line.split(":") for line in ["1:One", "2:Two", "4:Four"])

这篇关于如何以正确的顺序在Python中构造嵌套字典理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆