【发布时间】:2021-08-23 18:47:16
【问题描述】:
最近我一直在 python 中使用'yield'。而且我发现生成器函数非常有用。我的问题是,是否有一些东西可以减少生成器对象中的想象光标。只是 next(genfun) 如何移动和输出容器中的第 +i 个项目,我想知道是否存在任何可能调用类似 previous(genfun) 并移动到容器中的第 -1 个项目的函数。
实际工作
def wordbyword():
words = ["a","b","c","d","e"]
for word in words:
yield word
getword = wordbyword()
next(getword)
next(getword)
输出的
a
b
我希望看到和实现的是
def wordbyword():
words = ["a","b","c","d","e"]
for word in words:
yield word
getword = wordbyword()
next(getword)
next(getword)
previous(getword)
预期输出
a
b
a
这可能听起来很傻,但是生成器中是否有这个previous,如果没有,为什么会这样?为什么我们不能减少迭代器,或者我对现有方法一无所知,请稍加说明。什么是实现我手头的最接近的方法。
【问题讨论】:
-
还有
itertools.tee,它允许你多次迭代某些东西。实际上,它只是将中间体存储在幕后的列表中,但它与 Python 中的多通道生成器一样接近。
标签: python list function yield next