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 中构建嵌套字典理解
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
