获取发电机的子集 [英] Get a subset of a generator
问题描述
我有一个生成器函数,想从中获取前十项;我的第一次尝试是:
I have a generator function and want to get the first ten items from it; my first attempt was:
my_generator()[:10]
这是行不通的,因为错误无法告诉生成器,因此生成器不可下标.现在,我已经通过以下方法解决了这个问题:
This doesn't work because generators aren't subscriptable, as the error tells me. Right now I have worked around that with:
list(my_generator())[:10]
这有效,因为它将生成器转换为列表;但是,它效率低下,无法使用发电机.生成器是否有与[:10]
相同的内置Pythonic版本?
This works since it converts the generator to a list; however, it's inefficient and defeats the point of having a generator. Is there some built-in, Pythonic equivalent of [:10]
for generators?
推荐答案
import itertools
itertools.islice(mygenerator(), 10)
itertools
具有许多用于迭代器的实用程序. islice
使用开始,停止和步进参数来切片迭代器,就像切片列表一样.
itertools
has a number of utilities for working with iterators. islice
takes start, stop, and step arguments to slice an iterator just as you would slice a list.
这篇关于获取发电机的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!