列表推导泄漏了Python2中的循环变量:如何使其与Python3兼容 [英] List comprehensions leak their loop variable in Python2: how making it be compatible with Python3
本文介绍了列表推导泄漏了Python2中的循环变量:如何使其与Python3兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚从了解到了为什么列表推导内容是否写入循环变量,但是生成器不这样做吗? 列表推导也将其循环变量泄漏"到周围的范围内.
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
>>> x = 'before'
>>> a = [x for x in (1, 2, 3)]
>>> x
3
此错误已在Python3中修复.
This bug is fixed in 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兼容的最佳方法是什么?
What is the best way to make Python2 be compatible with Python3 at this point?
推荐答案
最好的方法通常是不重用这样的变量名,但是如果您希望某些东西能够同时在2和3中实现Python 3的行为,>
The best way is usually to just not reuse variable names like that, but if you want something that gets the Python 3 behavior in both 2 and 3:
list(x for x in (1, 2, 3))
这篇关于列表推导泄漏了Python2中的循环变量:如何使其与Python3兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文