Python列表解析覆盖值 [英] Python list comprehension overriding value

查看:118
本文介绍了Python列表解析覆盖值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看下面的代码段,显示列表解析。

have a look at the following piece of code, which shows a list comprehension..

>>> i = 6
>>> s = [i * i for i in range(100)]
>>> print(i)

Python 2.6中执行代码示例打印 99 ,但在 Python 3.x 中执行时,它会输出 6

When you execute the code example in Python 2.6 it prints 99, but when you execute it in Python 3.x it prints 6.

改变行为的原因是什么,为什么在 Python 3.x 中输出 6

What were the reason for changing the behaviour and why is the output 6 in Python 3.x?

提前感谢!

推荐答案

旧的行为是错误但不能轻易地修正为一些代码依赖它。

The old behaviour was a mistake but couldn't easily be fixed as some code relied on it.

列表解析中的变量 i 从顶层的不同 i 。逻辑上它应该有自己的范围,不会扩展到理解之外,因为它的价值只在理解内部有意义。但是在Python 2.x中,由于实现细节,范围大于必要的范围,导致变量泄漏到外部范围,导致您看到的混乱结果。

The variable i inside the list comprehension should be a different i from the one at the top level. Logically it should have its own scope which does not extend outside the comprehension as its value only makes sense inside the comprehension. But in Python 2.x due to an implementation detail the scope was larger than necessary causing the variable to "leak" into the outer scope, causing the confusing results you see.

Python 3.0故意不打算向前兼容以前的版本,因此他们利用这个机会来修正这种不良行为。

Python 3.0 was deliberately not intended to be backwards compatible with previous releases, so they used the opportunity to fix this undesirable behaviour.


在Python 2.3和更高版本,列表解析泄漏其每个的控制变量包含在包含范围中。但是,此行为已被弃用,依赖它将无法在Python 3.0中使用

In Python 2.3 and later releases, a list comprehension "leaks" the control variables of each for it contains into the containing scope. However, this behavior is deprecated, and relying on it will not work in Python 3.0

来源

这篇关于Python列表解析覆盖值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆