在列表理解或生成器表达式中使用 while
我可以在列表理解/生成器表达式中使用 if
和 for
因为
list(i for i in range(100) if i*i < 30)
我知道这不是最有效的,但请耐心等待,因为条件可能要复杂得多,这是只是一个例子。然而,这仍然会经历数百次迭代,并且只在前 6 次中产生一个值。有没有办法告诉生成器表达式在哪里停止,如下所示:
list(i for i in range(100) while i*i < 30)
然而, while
在生成器中不被理解表达式。所以,我的问题是,如何编写带有停止条件的生成器表达式,以便它不会继续计算,即使它不会产生新值。
I can use if
and for
in list comprehensions/generator expressions as
list(i for i in range(100) if i*i < 30)
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)
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
takewhile()
和dropwhile()
的语法不是最清晰,因此以下是您问题的实际示例:知道作者itertools 质疑是否弃用这些函数。
Because the syntax of
takewhile()
anddropwhile()
is not the clearest, here are the actual examples of your question:Know that the author of itertools has questioned whether to deprecate these functions.
itertools
中的各种函数 (takewhile()
浮现在脑海中)可以提供帮助。The various functions in
itertools
(takewhile()
comes to mind) can help.