在Python中将yield语句转换为Generator表达式 [英] Converting a yield statement to a Generator Expression in Python

查看:102
本文介绍了在Python中将yield语句转换为Generator表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对将yield语句转换为生成器表达式有疑问

I have a question regarding converting a yield statement to a generator expression

所以我有这个小的yield方法,它获取一个函数和一个起始数字作为输入,并且基本上为每个先前的数字调用该函数,即:

So I have this small yield method that gets a function and a starting number as its inputs, and basically calls the function for each previous number that was called i.e:

  • 第一个电话返回初始号码
  • 第二次调用返回函数(初始编号)
  • 第三个调用返回函数(第二个数字)
  • 第四个调用返回函数(第三个数字)

等 这是Python中的代码:

etc. Here is the code in Python:

def some_func(function, number):
    while True:
        yield number
        number = function(number)

将此代码段转换为生成器表达式的方式有哪些? 我猜想有一种非常Python化和优雅的方法可以做到这一点,但我只是无法理解.

What are the ways of converting this snippet into a Generator Expression? I'm guessing that there is a very pythonic and elegant way of doing this, but I just can't get my head around it.

我不太熟悉Generator Expressions,因此为什么我要寻求帮助,但是我确实想扩展我对Gen Exp的知识,尤其是对Python的了解

I am quite unfamiliar with Generator Expressions, hence why I'm asking for help but I do want to expand my knowledge of Gen Exp in general and of Python in particular

推荐答案

坚持现有的做法.您可以将函数转换为生成器表达式,但这会造成混乱.

Stick to what you have now. You could convert the function to a generator expression but it'd be an unreadable mess.

生成器表达式需要另一个可迭代的循环,而生成器函数则没有.生成器表达式实际上也没有访问任何其他变量的权限.只有表达式和循环,带有可选的if过滤器和更多循环.

Generator expressions need another iterable to loop over, which your generator function doesn't have. Generator expressions also don't really have access to any other variables; there is just the expression and the loop, with optional if filters and more loops.

这是生成器表达式的样子:

Here is what a generator expression would look like:

from itertools import repeat

number = [number]
gen = ((number[0], number.__setitem__(0, function(number[0]))[0] for _ in repeat(True))

我们将number用作变量".

这篇关于在Python中将yield语句转换为Generator表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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