>>> x = 'foo'
>>> {0: locals().get('x')}
{0: 'foo'}
>>> {0: locals().get('x' + spam) for spam in ['']}
{0: None}
Run Code Online (Sandbox Code Playgroud)
这种行为差异的原因是什么?
>>> a = 1
>>> print { key: locals()[key] for key in ["a"] }
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <dictcomp>
KeyError: 'a'
Run Code Online (Sandbox Code Playgroud)
如何创建一个像这样理解的字典?
我对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}
Run Code Online (Sandbox Code Playgroud)
在实际方面 …
我遇到了一个奇怪的情况。我想检查我的变量x, y, 是否z存在。
为此,我尝试了:
>>> [var in locals() for var in ["x", "y", "z"]]
[False, False, False]
Run Code Online (Sandbox Code Playgroud)
然后,我给你x,y,z一些值:
>>> x, y, z = 1, 2, 3
Run Code Online (Sandbox Code Playgroud)
尽管如此,我仍然有:
>>> [var in locals() for var in ["x", "y", "z"]]
[False, False, False]
Run Code Online (Sandbox Code Playgroud)
但是 x, y, z 一一存在:
>>> for var in ["x", "y", "z"]:
... print(var in locals())
...
True
True
True
Run Code Online (Sandbox Code Playgroud)
有人有解释吗?