Python zip object 'disappears' after iterating through?

后端 未结 3 1240
自闭症患者
自闭症患者 2020-12-10 14:33

Total noob question here but I really want to know the answer.

I have no idea why the zip object simply \"disappears\" after I attempt to iterate through it in its l

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-10 15:09

    zip creates an object for iterating once over the results. This also means it's exhausted after one iteration:

    >>> a = [1,2,3]
    >>> b = [4,5,6]
    >>> z = zip(a,b)
    >>> list(z)
    [(1, 4), (2, 5), (3, 6)]
    >>> list(z)
    []
    

    You need to call zip(a,b) every time you wish to use it or store the list(zip(a,b)) result and use that repeatedly instead.

提交回复
热议问题