如果我们要遍历的元素包含在多个序列中,如何对他们同时进行遍历>>> xpts=[1,5,3,2,6,7]>>> ypts=[101,105,103,102,106,107]>>> for x,y in zip(xpts,ypts):... print(x,y)...1 1015 1053 1032 1026 1067 107
- zip(a,b)原理是创建遍历器,该遍历器遍历出元组(x,y)这里x取自a序列,y取自b序列,当某个序列中没有元素可以遍历时,则停止遍历。如下,若ypts的元素比xpts的多则是如下情况
>>> ypts=[101,105,103,102,106,107,108]>>> for x,y in zip(xpts,ypts):... print(x,y)...1 1015 1053 1032 1026 1067 107>>>
- 如果我们想把所有元素都遍历到,则需要使用zip_longest()来替代
>>> from itertools import zip_longest>>> for i in zip_longest(xpts,ypts):... print(i)...(1, 101)(5, 105)(3, 103)(2, 102)(6, 106)(7, 107)(None, 108)>>>
|