Using while in list comprehension or generator expressions

后端 未结 2 1132
暗喜
暗喜 2020-11-30 08:42

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

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

I

相关标签:
2条回答
  • 2020-11-30 09:17

    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.

    0 讨论(0)
  • 2020-11-30 09:25

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

    0 讨论(0)
提交回复
热议问题