Python 2 和 Python 3 中的 for 有一点不一样
# Python2
>>> i = 1
>>> a = [i for i in range(4)]
>>> i
3
# Python3
>>> i = 1
>>> a = [i for i in range(4)]
>>> i
1
Python 2 中的 for 循环会污染全局变量,Python 3 不会。这个问题只会出现在列表推导式
中,对于普通的 for 循环,i 的值都是变的。对于集合推导式,i 的值不会变
# Python3
>>> i = 2
>>> a = {i for i in range(32)}
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
, 24, 25, 26, 27, 28, 29, 30, 31}
>>> i
2
# Python 2 和 Python 3 一样的结果
# Python2
>>> i = 3
>>> a = {i for i in range(6)}
>>> i
3
>>> i = 3
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
>>> i
4
网友评论