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 中构建嵌套字典理解
- YouTube API v3 返回截断的观看记录 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01