简体   繁体   English

在列表理解或生成器表达式中使用while

[英]Using while in list comprehension or generator expressions

I can use if and for in list comprehensions/generator expressions as 我可以使用iffor列表中的comprehensions / generator表达式作为

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. 但是, while在生成器表达式中不理解。 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. 所以,我的问题是,如何编写带有停止条件的生成器表达式,这样它就不会继续计算,即使它没有产生新的值。

Because the syntax of takewhile() and dropwhile() is not the clearest , here are the actual examples of your question: 因为takewhile()dropwhile()的语法不是最清楚的 ,所以这里是你问题的实际例子:

>>> [i for i in itertools.takewhile(lambda x: x*x<30, range(10))]
[0, 1, 2, 3, 4, 5]
>>> [i for i in itertools.dropwhile(lambda x: x*x<30, range(10))]
[6, 7, 8, 9] 

Know that the author of itertools has questioned whether to deprecate these functions. 知道itertools的作者质疑是否弃用这些函数。

itertools的各种函数( takewhile()在脑海中)可以提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM