您的位置:首页 > 编程语言 > Python开发

【Python学习笔记】-Python之zip()函数

2017-04-11 09:30 459 查看
zip()函数是Python内置的函数,具体用法如下:

首先使用help(zip)查看

Help on class zip in module builtins:

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


zip()函数会创建一个迭代器,聚合来自每个迭代器的元素。

返回一个由元组构成的迭代器,其中第i个元组包含来自每一组参数序列或可迭代量的第i元素。当最短输入可迭代被耗尽时,迭代器停止。使用单个可迭代参数,它返回1元组的迭代器。没有参数,它返回一个空迭代器。

等同于:

def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)


可以保证迭代按从左向右的计算顺序。这使得使用zip(*[iter(s)]*n)将数据序列聚类为n长度组的习语成为可能。这重复了相同的迭代器n次,以使每个输出元组具有对迭代器的n调用的结果。这具有将输入划分为n个长块的效果。

简单用法:

>>> x=[1,2]
>>> y=[3,4,5]
>>> z=zip(x,y)
>>> z
<zip object at 0x7f6819343c48>
>>> list(z)
[(1, 3), (2, 4)]


由上可知,直接调用z返回的是对象地址。多余的值会舍弃。

zip()应该只用于不等长的输入,当你不在乎较长的迭代的尾随,不匹配的值。如果这些值很重要,请改用itertools.zip_longest()。

zip() 与 * 操作符一起可以用来 unzip 一个列表:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: