为什么zip对象消失了?

it_*_*ure 3 python python-3.x

请查看代码,为什么列表(w)正确显示,并且h什么都不显示?

>>> x=[1,2,3]
>>> y=[4,5,6]
>>> w=zip(x,y)
>>> list(w)
[(1, 4), (2, 5), (3, 6)]
>>> h=list(w)
>>> h
[]
Run Code Online (Sandbox Code Playgroud)

use*_*740 7

在Python 3中,zip返回一个迭代器1.

使一个迭代其聚集来自每个iterables的元件.

迭代器会记住迭代的位置; 在该h=list(w)行,迭代器已经"在结尾",因此导致空列表/序列.

尝试使用w = list(zip(x,y)),这将强制迭代器到列表一次.


1 Python 2中的zip返回一个列表,因此这种行为仅在Python 3中展示.