>>> X = [1, 2, 3, 4, 5, 6]
>>> Y = [121, 223, 116, 666, 919, 2333]
>>> for x, y in zip(X, Y):
... print(x, y)
...
1 121
2 223
3 116
4 666
5 919
6 2333
>>> a = [1, 2, 3, 4, 5, 6]
>>> b = [‘x‘, ‘y‘, ‘z‘]
>>> for x, y in zip(a, b):
... print(x, y)
...
1 x
2 y
3 z
>>>
>>> a = [1, 2, 3, 4, 5, 6]
>>> b = [‘x‘, ‘y‘, ‘z‘]
>>> from itertools import zip_longest
>>> for i in zip_longest(a, b):
... print(i)
...
(1, ‘x‘)
(2, ‘y‘)
(3, ‘z‘)
(4, None) # 多余元素对应None
(5, None)
(6, None)
>>> for i in zip_longest(a, b, fillvalue=2): # 可以指定多余元素对应的值
... print(i)
...
(1, ‘x‘)
(2, ‘y‘)
(3, ‘z‘)
(4, 2) # 指定多余元素对应值为2
(5, 2)
(6, 2)
>>> from itertools import chain
>>> a = [1, 2, 3, 4, 5]
>>> b = [‘x‘, ‘y‘, ‘z‘]
>>> for i in chain(a, b):
... print(i)
...
1
2
3
4
5
x
y
z
3.合并多个有序序列,并对整个有序序列进行迭代
>>> from heapq import merge
>>> a = [1, 3, 4, 5, 7, 9]
>>> b = [2, 6, 8, 11, 13]
>>> for i in merge(a, b):
... print(i)
...
1
2
3
4
5
6
7
8
9
11
13