同时迭代多个序列
将多个序列结合起来一起迭代,可以使用内置的zip函数,如下:
>>> 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函数构造了一个每个元素为tuple (x, y)的迭代器,其中x取a可迭代对象,y取b可迭代对象中的元素。直到长度最小的那个可迭代对象耗尽为止。
若要以最长的元素为基准,则可以使用itertools的zip_longest方法,如下:
>>> a = [1, 2, 3]
>>> b = ['w', 'x', 'y', 'z']
>>> for i in zip(a,b):
... print(i)
(1, 'w')
(2, 'x')
(3, 'y')
>>>
>>> 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')
>>>