python - 列表理解在 Python2 : how making it be compatible with Python3 中泄漏了它们的循环变量

标签 python python-2.7 python-3.x list-comprehension compatibility

刚从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/

相关文章:

python - 在 pyplot/python 中绘图时如何强制散点点真实像素值?

python - 遍历包含重复值的列表

python-3.x - 如何在不使用 Pandas 的情况下创建相当于 numpy.nan 的日期时间对象?

python - 无法安装flask-mysqldb

AWS 上的 Python 网络抓取脚本在 1.5 小时/获取 10,000 个 xml 后一直失败

python - 从 Python 运行 SQL 文件

python - 在python中添加动态表名

python - RegEx 获取两个字符串之间有换行符的字符串

Python csv.DictReader 内存不足

python-3.x - 更新标签上的文本