获取发电机的子集 [英] Get a subset of a generator

查看:77
本文介绍了获取发电机的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个生成器函数,想从中获取前十项;我的第一次尝试是:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆