设置理解不符合预期

zha*_*min 3 python python-2.7 set-comprehension

需要帮助解释为什么此代码段不会像我期望的那样返回

>>> a = 1
>>> v = ["a", "b", "c"]
>>> {e for e in v if locals().get(e) is None}
set(['a', 'c', 'b'])
Run Code Online (Sandbox Code Playgroud)

我希望它能够返回set(['c', 'b']),就像我建立一个列表一样

>>> [e for e in v if locals().get(e) is None]
['b', 'c']
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

在Python 2中,set和dictionary comprehensions有自己的范围; locals()在这样的构造内部引用了新的嵌套范围.

列表推导没有,因为它们是在语言生命周期的早期实现的,之后开发人员意识到新的范围将是一个更好的想法.在Python 3中,列表推导也有自己的范围.

您可以通过创建对运行集合理解之前locals()返回的字典的单个引用来解决此问题:

>>> l = locals()
>>> {e for e in v if l.get(e) is None}
{'c', 'b'}
Run Code Online (Sandbox Code Playgroud)