One, reverse iteration: Reversed ()
>>> a[1, 2, 3, 4] for in reversed (a): ... Print (x, end="
#反向迭代只有在待处理的对象具有确定的大小或者对象实现了__reversed () __ Special methods to work, otherwise you must first convert the object to a list (may consume a lot of memory)
>>> with open ( " /etc/passwd , " RT " ) as file: ... for x # ... print (x) ... Traceback (most recent): File , Line 2, in < Module>typeerror:argument to reversed () must is a sequence
Second, iterator slicing: itertools.islice
Import Itertools def count (n): ... while True: ... yield N. ... n + = 1
... for in Itertools.islice (count (0), 2, ten): #相当于列表切片取 [2:10] ... Print (x, end="
>>>for x in Itertools.islice (count (0), 5 print (x, End= " ) ... if x >10: ... break ... 5 6 7 8 9 10>>> for x in Itertools.islice (count (0), 5 print (x, End= " ) ... 0 1 2 3 4
#迭代器和生成器无法进行普通的切片操作 (whose length is indeterminate and does not implement an index), Islice produces a new iterator that consumes all the data from the initial iteration sequence
Iii. iterative sequence in the form of index-value pairs: Enumerate
>>> a[1, 2, 3, 4] for in Enumerate (a, 1): # starting from 1 counts, Syntax: Enumerate (iterable[, start]) ... Print 1 12 23) 34 4
#enumerate的返回值是一个迭代器, the element is a tuple
Iv. simultaneous iteration of multiple sequences
Parallel paired iterations: Zip (), itertools.zip_longest ()
>>>a[1, 2, 3, 4]>>>b[1, 2, 3, 4, 8, 9]>>> forX, yinchZip (A, b): ...Print(x, y) ...1 4>>> forX, yinchItertools.zip_longest (A, B): ...Print(x, y) ...1 12 23) 34 4None8None9>>> forX, yinchItertools.zip_longest (A, B, fillvalue=0): ...Print(x, y) ...1 12 23) 34 40809
Serial Sequential iterations: Itertools.chain ()
for inch Itertools.chain (A, B): ... Print 1234123489
Serial Cross Iteration: Heapq.merge ()
Import HEAPQ for inch Heapq.merge (A, B): ... Print 1122334489
Python3 from zero--{initial consciousness: 004~ iterators and generators}