イテレータスライシング操作

イテレータオブジェクトは、一般イテラブル(リスト、タプル、等)のようなスライスでサポートされていません。
次の例:

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

おすすめ

転載: www.cnblogs.com/jeffrey-yang/p/11808977.html