Using while in list comprehension or generator expressions

旧巷老猫 提交于 2019-11-27 04:37:34

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

Because the syntax of takewhile() and dropwhile() is not the clearest, here are the actual examples of your question:

>>> [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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!