一、反向迭代:reversed()
>>> a
[1, 2, 3, 4]
>>> for x in reversed(a):
... print(x, end=' ')
...
4 3 2 1
#反向迭代只有在待处理的对象具有确定的大小或者对象实现了__reversed()__特殊方法时才能奏效,否则必须先将对象转化为列表(可能消耗大量内存)
>>> with open('/etc/passwd', 'rt') as file:
... for x in reversed(file): #要用list(file)
... print(x)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: argument to reversed() must be a sequence
二、迭代器切片:itertools.islice
import itertools
>>> def count(n):
... while True:
... yield n
... n += 1
...
>>> for x in itertools.islice(count(0), 2, 10): #相当于列表切片取[2:10]
... print(x, end=' ')
...
2 3 4 5 6 7 8 9
>>>for x in itertools.islice(count(0), 5, None): #相当于列表切片取[5:]
... print(x, end=' ')
... if x >10:
... break
...
5 6 7 8 9 10
>>> for x in itertools.islice(count(0), 5): #相当于列表切片取[:5]
... print(x, end=' ')
...
0 1 2 3 4
#迭代器和生成器无法进行普通的切片操作(其长度不确定且没有实现索引),islice会产生一个新迭代器,消耗掉初始迭代序列中的所有数据
三、以索引-值对的形式迭代序列:enumerate
>>> a
[1, 2, 3, 4]
>>> for index, value in enumerate(a, 1): #从1开始计数,语法:enumerate(iterable[, start])
... print(index, value)
...
1 1
2 2
3 3
4 4
#enumerate的返回值是一个迭代器,元素是元组
四、同时迭代多个序列
并行成对迭代:zip()、itertools.zip_longest()
>>> a
[1, 2, 3, 4]
>>> b
[1, 2, 3, 4, 8, 9]
>>> for x, y in zip(a, b):
... print(x, y)
...
1 1
2 2
3 3
4 4
>>> for x, y in itertools.zip_longest(a, b):
... print(x, y)
...
1 1
2 2
3 3
4 4
None 8
None 9
>>> for x, y in itertools.zip_longest(a, b, fillvalue=0):
... print(x, y)
...
1 1
2 2
3 3
4 4
0 8
0 9
串行顺序迭代:itertools.chain()
>>> for x in itertools.chain(a, b):
... print(x)
...
1
2
3
4
1
2
3
4
8
9
串行交叉迭代:heapq.merge()
>>> import heapq
>>> for x in heapq.merge(a, b):
... print(x)
...
1
1
2
2
3
3
4
4
8
9