任何时候你想要一个迭代器。这就是iter 的用途,它为您传递给它的内容返回一个迭代器。因此,请考虑以下生成器,它利用了迭代器的属性,即它是单次传递且可耗尽的,从迭代器中提取迭代器应该返回迭代器本身,而不是给你一个新的。
In [19]: import itertools
In [20]: def chunk_by_n(iterable, n):
...: islice = itertools.islice
...: iterator = iter(iterable)
...: chunk = list(islice(iterator, n))
...: while chunk:
...: yield chunk
...: chunk = list(islice(iterator, n))
...:
In [21]: iterable = range(100)
In [22]: chunks = chunk_by_n(iterable, 3)
In [23]: next(chunks)
Out[23]: [0, 1, 2]
In [24]: next(chunks)
Out[24]: [3, 4, 5]
In [25]: next(chunks)
Out[25]: [6, 7, 8]
现在,看看如果我们不从输入中创建一个迭代器会发生什么:
In [26]: def chunk_by_n(iterable, n):
...: islice = itertools.islice
...: #iterator = iter(iterable)
...: iterator = iterable
...: chunk = list(islice(iterator, n))
...: while chunk:
...: yield chunk
...: chunk = list(islice(iterator, n))
...:
In [27]: chunks = chunk_by_n(iterable, 3)
In [28]: next(chunks)
Out[28]: [0, 1, 2]
In [29]: next(chunks)
Out[29]: [0, 1, 2]
In [30]: next(chunks)
Out[30]: [0, 1, 2]