如何展望Python生成器中的一个元素(预览)? [英] How to look ahead one element (peek) in a Python generator?

查看:116
本文介绍了如何展望Python生成器中的一个元素(预览)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何展望Python生成器中的一个元素.我一看就消失了.

I can't figure out how to look ahead one element in a Python generator. As soon as I look it's gone.

这是我的意思:

gen = iter([1,2,3])
next_value = gen.next()  # okay, I looked forward and see that next_value = 1
# but now:
list(gen)  # is [2, 3]  -- the first value is gone!

这是一个更真实的例子:

Here is a more real example:

gen = element_generator()
if gen.next_value() == 'STOP':
  quit_application()
else:
  process(gen.next())

有人能帮我写一个生成器,让您向前看一个元素吗?

Can anyone help me write a generator that you can look one element forward?

推荐答案

Python生成器API是一种方式:您不能回退已读取的元素.但是您可以使用 itertools模块创建一个新的迭代器,并在元素之前添加

The Python generator API is one way: You can't push back elements you've read. But you can create a new iterator using the itertools module and prepend the element:

import itertools

gen = iter([1,2,3])
peek = gen.next()
print list(itertools.chain([peek], gen))

这篇关于如何展望Python生成器中的一个元素(预览)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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