刚从Why do list comprehensions write to the loop variable, but generators don't?中了解到列表推导也将它们的循环变量“泄漏”到周围的范围内。
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
>>> x = 'before'
>>> a = [x for x in (1, 2, 3)]
>>> x
3
此错误已在 Python3 中修复。
Python 3.4.3 (default, Oct 14 2015, 20:28:29)
>>> x = 'before'
>>> a = [x for x in (1, 2, 3)]
>>> x
'before'
此时使 Python2 与 Python3 兼容的最佳方法是什么?
最佳答案
最好的方法通常是不要像那样重用变量名,但是如果你想要在 2 和 3 中都获得 Python 3 行为的东西:
list(x for x in (1, 2, 3))
关于python - 列表理解在 Python2 : how making it be compatible with Python3 中泄漏了它们的循环变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37887289/