内置函数zip()

zip有拉链的意思,zip函数像拉链一样将0个或多个可迭代对象按相同位置组合成一个zip对象,该zip对象的每个元素是由每个可迭代对象的相同位置的元素组成的元祖。

如果zip中有多个序列,而各序列的长度不同,那么返回的对象的长度以最短为准,超出的部分不返回。

如果zip中只有一个序列,则返回对象的每个元祖中只有一个元素。如果zip没有给参数,那么返回一个空对象。

用法:

zip(*iterables)
Make an iterator that aggregates elements from each of the iterables.

Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. 
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [7,8,9,10]

>>> zip(a,b)
<zip object at 0x00000000027D2FC8>
>>> z=zip(a,b)
>>> print(z)
<zip object at 0x00000000027D6088>

>>> for i in z:
... 	print(i)
... 
(1, 4)
(2, 5)
(3, 6)
>>> x=zip(a)
>>> for i in x:
... 	print(i)
... 
(1,)
(2,)
(3,)
>>> y=zip(a,b,c)
>>> for i in y:
... 	print(i)
... 
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)

另外zip函数可以使用星号解开zip对象,即unzip。

zip() in conjunction with the * operator can be used to unzip a list.
>>> m=zip(*zip(a,b,c))
>>> for i in m:
... 	print(i)
... 
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)

参考:https://docs.python.org/3/library/functions.html#zip

posted @ 2017-10-08 23:33  KeithTt  阅读(394)  评论(0编辑  收藏  举报