在列表理解或生成器表达式中使用while [英] Using while in list comprehension or generator expressions

查看:185
本文介绍了在列表理解或生成器表达式中使用while的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在列表推导/生成器表达式中使用iffor作为

I can use if and for in list comprehensions/generator expressions as

list(i for i in range(100) if i*i < 30)

我知道这不是最有效的方法,但是请耐心等待,因为条件可能要复杂得多,这只是一个例子.但是,这仍然要经过一百次迭代,并且只会在前6个中产生一个值.是否可以通过类似这样的方式告诉生成器表达式在哪里停止:

I know this is not the most efficient but bear with me as the condition could be much more complicated and this is just an example. However, this still goes through hundred iterations and only yields a value in the first 6. Is there a way to tell the generator expression where to stop with something like this:

list(i for i in range(100) while i*i < 30)

但是,生成器表达式中不理解while.因此,我的问题是,如何编写具有停止条件的生成器表达式,以便即使不产生新值也不会继续计算.

However, while is not understood in generator expressions. So, my question is, how do I write a generator expression with a stopping condition so it does not continue computation, even if it doesn't yield new values.

推荐答案

(想到了takewhile())可以提供帮助.

The various functions in itertools (takewhile() comes to mind) can help.

这篇关于在列表理解或生成器表达式中使用while的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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