对dict理解中的locals()下标失败,并出现KeyError

马泰奥·费拉(Matteo Ferla)

我对Python的奇怪行为感到困惑locals()
基本上,我想从locals()字典理解中的字典中获得一个项目,但是失败了。这是非常基本的事情,因此:

>>> foo=123
>>> bar=345
>>> baz=678
>>> {k: locals()[k] for k in ('foo','bar','baz')}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <dictcomp>
KeyError: 'foo'
>>> locals()['foo']
123
>>> locale=locals()
>>> {k: locale[k] for k in ('foo','bar','baz')}
{'foo': 123, 'bar': 345, 'baz': 678}
>>> type(locals())
<class 'dict'>
>>> def fun():
...     return {'foo': 123,'bar':345}
... 
>>> {k: fun()[k] for k in ('foo','bar')}
{'foo': 123, 'bar': 345}

从实际的角度来看{'foo':foo, 'bar': bar},字典或字符串中的丑陋.format()效果很好。
只是我缺少了一些东西,所以知道为什么会增加我的编码能力(到目前为止,我在编码时不发光)。

迪米特里斯·法萨拉基斯·希利亚德

由于Python 3中的所有理解都是使用隐藏函数实现的,因此调用locals不会返回您期望其返回的值。

您可以通过将值打印出来来查看:

>>> _ = {k: print(locals()) for k in ('foo','bar','baz')}
{'k': 'foo', '.0': <tuple_iterator object at 0x7fdf840afa90>}
{'k': 'bar', '.0': <tuple_iterator object at 0x7fdf840afa90>}
{'k': 'baz', '.0': <tuple_iterator object at 0x7fdf840afa90>}

分配locals()locale您,就像您所做的那样。您不是locals在理解内线。


请注意,在Python 2中,情况有点模糊。dict-comps确实会以类似的方式失败,但是在dict-comps之前的list-comps可以正常工作:

>>> _ = [locals()[k] for k in ('foo', 'bar', 'baz')]
>>> _
[20, 40, 60]

这是Py3解决的另一个“缺陷”

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

来自locals()的Python getattr失败,并出现AttributeError

在Spring 5中Jetty:run失败并出现NoSuchMethodError

在启动中启用CORS失败,并出现预检错误

gcloud组件更新在MacOS中失败,并出现UnicodeDecodeError

Git在Visual Studio中失败并出现致命错误

编译失败并出现错误

ElasticsearchIntegrationTest失败,并出现NullPointerException

失败:构建失败并出现异常。

Python失败,出现KeyError

rubymine提交失败并出现错误

创建MethodNode失败,并出现IllegalStateException

Apache Spark MultilayerPerceptronClassifier失败,并出现ArrayIndexOutOfBoundsException

Gradle项目同步失败,并出现ParseError

如何确保insmod失败并出现错误?

Mocha测试失败并出现AssertionError

清单合并失败,并出现多个错误

安装gem失败并出现超时错误

Buildozer失败,并出现numpy要求

Vuex + Jest测试失败并出现TypeError

从 Azure 登录失败并出现 BadRequest

在CMD中运行时,脚本失败并出现AttributeError,但在IDLE中执行正常

迭代 bash 中的文件,在 Jenkins 管道中,失败并出现 MissingPropertyException

为什么会出现TypeError:“ int”对象无法使用for循环下标,而不能与python中的列表理解下标

Netty / Armeria处理程序方法中的Bootstrap Hibernate SessionFactory失败,并出现ClassNotFoundException

有时在 Kusto 中获取摄取失败,并出现错误 -“Stream_WrongNumberOfFields”

Android Studio中的构建成功,但使用“ gradlew构建”构建失败,并出现NullPointerException

当 jmeter 中的线程数增加时,请求失败并出现错误 400

仅在py.test文件中,使用嵌套(单词?)导入的变量/函数失败,并出现NameError

AES解密在中文语言环境中失败,并出现无效字符错误