How to construct nested dictionary comprehension in Python with correct ordering?(如何以正确的顺序在 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
而且,当我像这样反转 for
语句时
And, when I reverse the for
statements like this
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
我需要关于dictionary
(或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()
表达式返回两个项的序列,但这些项中的每一项都不是键和值的元组;相反,只有 one 元素被迭代.将拆分包装在一个元组中,以便生成 (key, value)
项目的序列"以将两个结果分配给两个项目:
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 中构建嵌套字典理解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何以正确的顺序在 Python 中构建嵌套字典理解
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01