[英]Python unexpected behaviour
如下代码:
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])
获得新的迭代器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.