Python列表理解中泄漏的变量

示例

Python 2.x 2.3
x = 'hello world!'
vowels = [x for x in 'AEIOU'] 

print (vowels)
# 输出:['A','E','I','O','U']
print(x)
# 出:'U'
Python 3.x 3.0
x = 'hello world!'
vowels = [x for x in 'AEIOU']

print (vowels)
# 输出:['A','E','I','O','U']
print(x)
# 出:“你好,世界!”

从示例中可以看出,在Python 2中,的值x被泄漏:它被屏蔽hello world!并打印出U,因为这是x循环结束时的最后一个值。

但是,在Python 3中x打印原始定义的hello world!,因为列表理解中的局部变量不会掩盖周围范围的变量。

此外,生成器表达式(从2.5版开始在Python中可用),字典或集合理解(从Python 3反向移植到Python 2.7)都没有泄漏Python 2中的变量。

请注意,在Python 2和Python 3中,使用for循环时,变量都会泄漏到周围的范围内:

x = 'hello world!'
vowels = []
for x in 'AEIOU':
    vowels.append(x)
print(x)
# 出:'U'