Print all even numbers in a list until a given number

后端 未结 6 1073
别跟我提以往
别跟我提以往 2020-12-12 05:38

I am just beginning to dabble in Python, and have started to go through the chapters on learnpython.org. In the \'Loops\' chapter, I have solved the challenge with the follo

6条回答
  •  猫巷女王i
    2020-12-12 06:39

    Another method is using itertools which always comes in useful some way or another:

    >>> from itertools import takewhile, ifilter
    >>> not_237 = takewhile(lambda L: L != 237, numbers)
    >>> is_even = ifilter(lambda L: L % 2 == 0, not_237)
    >>> list(is_even)
    [402, 984, 360, 408, 980, 544, 390, 984, 592, 236, 942, 386, 462, 418, 344, 236, 566, 978, 328, 162, 758, 918]
    

    So we create a lazy iterator that stops at 237, then take from that even numbers

提交回复
热议问题