一个关于zip()函数的奇怪问题
代码如下:In : a = zip((1,2,3),('a','b','c'))
In : a
Out: <zip at 0xb655c0ec>
In : list(a)
Out: [(1, 'a'), (2, 'b'), (3, 'c')]
In : list(a)
Out: []
为什么第二次调用list(a)的时候,返回的是一个空列表呢?
python 3与以前的版本不同,返回的是迭代器,只能单次使用。 强答一下(我zip用的很少),希望对楼主有用
依据help(zip), 可以看到zip对象具备迭代性(__iter__,__next__)
>>> a = zip((1,2),(3,4))
>>> for i in a:
print(i)
(1, 3)
(2, 4)#数据访问结束后,触发 StopIteration。这个就是楼主遇到现象的原因
>>> type(a)
<class 'zip'>
class zip(object)
|zip(iter1 [,iter2 [...]]) --> zip object
|
|Return a zip object whose .__next__() method returns a tuple where
|the i-th element comes from the i-th iterable argument.The .__next__()
|method continues until the shortest iterable in the argument sequence
|is exhausted and then it raises StopIteration.
|
|Methods defined here:
|
|__getattribute__(self, name, /)
| Return getattr(self, name).
|
|__iter__(self, /)
| Implement iter(self).
|
|__new__(*args, **kwargs) from builtins.type
| Create and return a new object.See help(type) for accurate signature.
|
|__next__(self, /)
| Implement next(self).
|
|__reduce__(...)
| Return state information for pickling.
thexiosi 发表于 2018-5-22 11:14
强答一下(我zip用的很少),希望对楼主有用
依据help(zip), 可以看到zip对象具备迭代性(__iter__,__ne ...
还是有点不明白英文看不懂~~ 冬雪雪冬 发表于 2018-5-22 08:17
python 3与以前的版本不同,返回的是迭代器,只能单次使用。
还有有点不明白~ yuandiyuandi123 发表于 2018-5-22 15:00
还是有点不明白英文看不懂~~
简单来说:zip返回的是单次迭代器,读取完毕后结束
thexiosi 发表于 2018-5-22 15:06
简单来说:zip返回的是单次迭代器,读取完毕后结束
哦那明白啦 yuandiyuandi123 发表于 2018-5-22 15:01
还有有点不明白~
以前的版本zip是元组,可以反复用。而新版为什么做成单次使用的,主要是为了节省内存提高效率,每次__next__都只生成一个元素,而不是整个元组。 冬雪雪冬 发表于 2018-5-22 15:43
以前的版本zip是元组,可以反复用。而新版为什么做成单次使用的,主要是为了节省内存提高效率,每次__nex ...
明白啦谢谢~
页:
[1]