python生成器无休止的流而不使用yield [英] python generator endless stream without using yield

查看:59
本文介绍了python生成器无休止的流而不使用yield的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定函数f和初始值x的情况下,我试图生成无穷无尽的结果流 因此,第一个调用应给出初始值,第二个调用应给出f(x),第三个调用应为f(x2),而x2是f(x)的前一个结果,依此类推.

i'm trying to generate an endless stream of results given a function f and an initial value x so first call should give the initial value, second call should give f(x), third call is f(x2) while x2 is the previous result of f(x) and so on..

我想出了什么:

def generate(f, x): 
   return itertools.repeat(lambda x: f(x))

这似乎不起作用.有任何想法吗? (我不能在代码中使用yield).我也不能使用多于1行的代码来解决这个问题.任何帮助将不胜感激.

which does not seem to work. any ideas? (i cant use yield in my code). also i cant use more than 1 line of code for this problem. any help would be appreciated.

还请注意,在以前的版本中.我被要求使用产量.没问题:

also note that in a previous ex. i was asked to use the yield. with no problems:

while True:
    yield x
    x = f(x)

这很好用.但是现在..没有线索怎么办

this works fine. but now.. no clue how to do it without

推荐答案

在Python 3.3中,您可以使用itertools.accumulate:

In Python 3.3, you can use itertools.accumulate:

import itertools

def generate(f, x):
  return itertools.accumulate(itertools.repeat(x), lambda v,_:f(v))

for i, val in enumerate(generate(lambda x: 2*x, 3)):
  print(val)
  if i == 10:
    break

这篇关于python生成器无休止的流而不使用yield的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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