Python的意外行为

问题描述 投票:2回答:1

下面的代码:

coords = zip([0], [0])
for a, b in list(coords):
    print("{}, {}".format(a, b))

输出0, 0如预期。但是,下面的代码:

coords = zip([0], [0])
mylist = list(coords)
for a, b in list(coords):
    print("{}, {}".format(a, b))

输出什么。为什么会这样?

Python版本:

Python 3.6.3 |Anaconda, Inc.| (default, Oct 13 2017, 12:02:49) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
python
1个回答
4
投票

因为zip返回迭代器,这意味着一旦你迭代它,它用尽,您可以通过它再不能重复。

当你成为一个list你的第一次迭代正在做的:

mylist = list(coords)
# At this point coords has been exhausted, so any further `__next__` calls will just raise a `StopIteration`

当您尝试遍历它再次使用for循环,它不会产生任何更多的项目,因为没有什么别的返回。一切都已经使用list迭代。

为了让您的for循环工作,您需要:

  • 遍历mylist,这是一个list,因此它保持了项目的索引(可随机访问的),这意味着你可以在所有的元素很多次,只要你想。
  • 获取再次调用zip([0], [0])新鲜的迭代器。
© www.soinside.com 2019 - 2024. All rights reserved.