迭代器切片操作

耗尽温柔 提交于 2019-12-03 21:05:34

迭代器对象一般来说是不支持像可迭代对象(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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!