迭代器切片操作

迭代器对象一般来说是不支持像可迭代对象(list,tuple等)的切片操作。
如下示例:

def count(n):
   while True:
       yield n
       n += 1

c = count(0)
c[10:20]
Trackback(most recent call last):
   File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable

itertools模块提供了对迭代器对象的切片操作支持,itertools提供了模块级函数islice。

import itertools
for x in itertools.islice(c, 10, 20):
    print(x)
...
10
11
12
13
14
15
16
17
18
19
上一篇:使用itertools产品时生成随机数


下一篇:python – 匹配列表中的元素,然后在它之前返回`n`元素,在它之后返回`m`元素