每次分别从一个序列中取一个元素
>>> xpts = [1, 5, 4, 2, 10, 7] >>> ypts = [101, 78, 37, 15, 62, 99] >>> for x, y in zip(xpts, ypts): ... print(x,y) ... 1 101 5 78 4 37 2 15 10 62 7 99 >>>
zip(a, b) 会生成一个可返回元组(x, y) 的迭代器,其中x 来自a,y 来自b。一旦其中某个序列到底结尾,迭代宣告结束。因此迭代长度跟参数中最短序列长度一致。
>>> a = [1, 2, 3] >>> b = ['w', 'x', 'y', 'z'] >>> for i in zip(a,b): ... print(i) ... (1, 'w') (2, 'x') (3, 'y')
如果这个不是你想要的效果,那么还可以使用itertools.zip longest() 函数来代替。比如:
>>> from itertools import zip_longest >>> for i in zip_longest(a,b): ... print(i) ... (1, 'w') (2, 'x') (3, 'y') (None, 'z')
>>> for i in zip_longest(a, b, fillvalue=0): ... print(i) ... (1, 'w') (2, 'x') (3, 'y') (0, 'z')