下面的代码:
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.
因为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])
新鲜的迭代器。