Python内置一个zip函数,这里不是压缩的意思,而是将数据组合在一起,zip起来,zip本身就还有拉链的意思哦。那么,zip这个函数,组合什么呢?将多个序列组合成一个复合序列。
看下面示例代码:
>>>
>>> listA = [1,2,3]
>>> listB = [4,5,6]
>>> listA
[1, 2, 3]
>>> listB
[4, 5, 6]
>>> zip(listA,listB)
>>> list(zip(listA,listB))
[(1, 4), (2, 5), (3, 6)]
>>>
>>> listB.append(7)
>>> listB
[4, 5, 6, 7]
>>> list(zip(listA,listB))
[(1, 4), (2, 5), (3, 6)]
>>>
>>> list(zip(listA))
[(1,), (2,), (3,)]
>>>
>>> list(zip('abcd','12345'))
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
>>>
>>> tuple(zip('abcd','12345'))
(('a', '1'), ('b', '2'), ('c', '3'), ('d', '4'))
>>>
>>>
官方对zip函数的解释:
zip(iter1 [,iter2 [...]]) --> zip object
Return a zip object whose .__next__() method returns a tuple wherethe i-th element comes from the i-th iterable argument. The .__next__()method continues until the shortest iterable in the argument sequenceis exhausted and then it raises StopIteration.
超过两个iterable的参数也是可以的:
>>>
>>> k = zip([1,2,3],[4,5,6],[7,8,9])
>>> k
>>> list(k)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>>