python itertools islice对迭代器做切片操作

2022-05-15  本文已影响0人  孙广宁
4.7 如何对迭代器和生成器做切片操作。
>>> def c(n):
...     while True:
...         yield n
...         n+=1
...
>>> c = c(0)
>>> c
<generator object c at 0x104beff50>
>>> c[10:20]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'generator' object is not subscriptable
>>>
>>> import itertools
>>> for x in itertools.islice(c,10,20):
...     print(x)
...
10
11
12
13
14
15
16
17
18
19
>>>
上一篇 下一篇

猜你喜欢

热点阅读