当我们使用python2运行下面的代码时,结果是
[(1, 2), (2, 3), (3, 4)]
m: 1, n: 2
m: 2, n: 3
m: 3, n: 4
否则,使用 python3
[(1, 2), (2, 3), (3, 4)]
我觉得python3的结果没有意义?谁能告诉我为什么?
a = [1, 2, 3]
b = [2, 3, 4]
c = zip(a,b)
print(list(c))
for (m,n) in list(c):
print('m: {}, n: {}'.format(m, n))
最佳答案
在 Python 3 中,zip
(以及其他一些函数,例如 map
)返回一次性迭代器。那么,发生的事情是这样的:
- 您定义了
c = zip(a, b)
,但c
尚未被计算(这意味着对a
和b
此时不会发生)。 print(list(c))
迭代c
的元素,直到到达迭代器的末尾。c
现在已“耗尽”:>>> a = [1, 2, 3] >>> b = [2, 3, 4] >>> c = zip(a,b) >>> print(list(c)) [(1, 2), (2, 3), (3, 4)] >>> next(c) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
看看调用
next(c)
如何引发StopIteration
吗?这正是您第二次调用list(c)
时发生的情况,因此它返回一个空列表:>>> list(c) []
解决这个困境的一个解决方案是立即将迭代器转换为列表(并且仅一次):
a = [1, 2, 3]
b = [2, 3, 4]
c = list(zip(a,b))
print(c)
for (m,n) in c:
print('m: {}, n: {}'.format(m, n))
关于python - 为什么代码在 python2 和 python3 中有不同的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60952677/