已经有Python生成器可以做这些基本的事情了吗?

发布于 2024-11-30 11:37:58 字数 717 浏览 1 评论 0原文

我发现自己使用这两个自定义生成器并思考“必须有一个 itertools 函数或已经做到这一点的东西!但没有找到任何东西。我错过了什么吗?谢谢!

def gothru(iters):
  for i in iters:
    for j in i:
      yield j

def overnover(fn,startval):
  val = startval
  while True:
    val = fn(val)
    yield val

编辑:我后来想象如何overnover 可用于生成斐波那契数列,我意识到需要对其进行泛化以允许该函数具有多个参数,

def overnover(fn,*args):
  while True:
    args = fn(*args)
    return args

然后您可以执行以下操作:

fibInfo = overnover(lambda x,y: (x+y, x), 1, 1)

-> (2,1) ... ( 3、 2) ... (5, 3) ... (8, 5) ... 然后:

fib = imap(lambda x:x[0], fibInfo)

-> 2 ... 3 ... 5 ... 8 ...

谢谢大家!

I found myself using these 2 custom generators and thinking "there's got to be an itertools function or something that already does this! Didn't find any though. Am I missing something? Thanks!

def gothru(iters):
  for i in iters:
    for j in i:
      yield j

def overnover(fn,startval):
  val = startval
  while True:
    val = fn(val)
    yield val

EDIT: i was later imagining how overnover could be used to generate the fibonacci sequence, and i realized that it would need to be generalized to allow the function to have more than one argument

def overnover(fn,*args):
  while True:
    args = fn(*args)
    return args

then you could do:

fibInfo = overnover(lambda x,y: (x+y, x), 1, 1)

-> (2,1) ... (3, 2) ... (5, 3) ... (8, 5) ...
and then:

fib = imap(lambda x:x[0], fibInfo)

-> 2 ... 3 ... 5 ... 8 ...

thanks guys!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

度的依靠╰つ 2024-12-07 11:37:58

第一个是 chain.from_iterable

overnover最接近的是tabulate

def tabulate(function, start=0):
    "Return function(0), function(1), ..."
    return imap(function, count(start))

这是函数的一种特殊情况,它输出连续的数字。 count 也需要一个 step,因此您可以将其概括为

def tabulate(function, start=0, step=1):
    "Return function(0), function(0+step), ..."
    return imap(function, count(start, step))

以下是 overnover 的一个版本,它可以让您将值发送到序列中:

def overnover(fn, val):
    while True:
        val = fn(val)
        val = (yield val) or val

The first one is chain.from_iterable.

The closest thing to overnover is something like tabulate:

def tabulate(function, start=0):
    "Return function(0), function(1), ..."
    return imap(function, count(start))

which is a special case of your function where it outputs sequential numbers. count also takes a step, so you could generalize this to

def tabulate(function, start=0, step=1):
    "Return function(0), function(0+step), ..."
    return imap(function, count(start, step))

Here is a version of overnover that would let you send values into the sequence:

def overnover(fn, val):
    while True:
        val = fn(val)
        val = (yield val) or val
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文