python - 为什么代码在 python2 和 python3 中有不同的行为?

标签 python

当我们使用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 尚未被计算(这意味着对 ab 此时不会发生)。
  • 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/

相关文章:

python - "Replace all"之后撤消

python - 在python中杀死sudo启动的子进程

python - 根据列表中列的值过滤 Pandas 数据框列

python - 单个应用程序的 Django URL 路由

python - TypeError: start() 恰好接受 1 个参数(给定 0)?

javascript - 我如何获得更多位置?

Python SciPy UnivariateSpline 返回 NaN - 范围内的值

python - 给定文件路径时查找最高深度

python - 查看字符串是否包含不同数据帧中的子字符串

python - 如何从字典列表中的字典中获取值