[PythonCookBook] [イテレーターとジェネレーター]イテレーターのスライス

従来の考え方でイテレータをスライスする

実際、イテレータはリストのようにスライスすることはできません

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

counter = count(0)
print(counter[10:20])

#执行结果如下列打印,生成器是不可以被切片的。
'''
Traceback (most recent call last):
  File "C:/Users/Administrator/PycharmProjects/Training/venv/ForBlog/迭代器切片.py", line 8, in <module>
    print(counter[10:20])
TypeError: 'generator' object is not subscriptable

Process finished with exit code 1
'''

解決

itertoolsを使用して、スライス操作のためにisliceを呼び出します

import itertools

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

counter =count(0)

for i in itertools.islice(counter, 10, 20):
    print(i)

#输出结果如下列打印所示
10
11
12
13
14
15
16
17
18
19

Process finished with exit code 0

おすすめ

転載: blog.csdn.net/qq_33868661/article/details/114974374