遍历后,Python zip对象“消失"了吗? [英] Python zip object 'disappears' after iterating through?
问题描述
这里有新手提问,但我真的很想知道答案.
Total noob question here but I really want to know the answer.
我不知道为什么在尝试以列表形式遍历zip对象后,它只是简单地消失"了: 例如.
I have no idea why the zip object simply "disappears" after I attempt to iterate through it in its list form: eg.
>>> A=[1,2,3]
>>> B=['A','B','C']
>>> Z=zip(A,B)
>>> list(Z)
>>> [('C', 3), ('B', 2), ('A', 1)]
>>> {p:q for (p,q) in Z}
{1: 'A', 2: 'B', 3: 'C'}
>>> {p:q for (p,q) in list(Z)}
{}
>>> list(Z)
[]
(这是在Python 3.4.2中)
(this is in Python 3.4.2)
有人可以帮忙吗?
推荐答案
Python2与Python3之间的行为发生了变化:
在python2中,zip返回元组列表,而在python3中,返回<一个href ="https://docs.python.org/3/library/functions.html#zip" rel ="noreferrer">迭代器.
There was a change of behavior between Python2 to Python3:
in python2, zip returns a list of tuples while in python3 it returns an iterator.
迭代器的本质是,一旦完成对数据的迭代,它将指向一个空集合,这就是您所经历的行为.
The nature of iterator is that once it's done iterating the data - it points to an empty collection and that's the behavior you're experiencing.
Python2 :
Python 2.7.9 (default, Jan 29 2015, 06:28:58)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> A=[1,2,3]
>>> B=['A','B','C']
>>> Z=zip(A,B)
>>> Z
[(1, 'A'), (2, 'B'), (3, 'C')]
>>> list(Z)
[(1, 'A'), (2, 'B'), (3, 'C')]
>>> list(Z)
[(1, 'A'), (2, 'B'), (3, 'C')]
>>> list(Z)
[(1, 'A'), (2, 'B'), (3, 'C')]
>>> {p:q for (p,q) in Z}
{1: 'A', 2: 'B', 3: 'C'}
>>> Z
[(1, 'A'), (2, 'B'), (3, 'C')]
>>> Z
[(1, 'A'), (2, 'B'), (3, 'C')]
Python3 :
Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 5 2014, 20:42:22)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> A=[1,2,3]
>>> B=['A','B','C']
>>> Z=zip(A,B)
>>> list(Z)
[(1, 'A'), (2, 'B'), (3, 'C')]
>>> list(Z)
[]
>>>
这篇关于遍历后,Python zip对象“消失"了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!