Print all even numbers in a list until a given number

后端 未结 6 972
别跟我提以往
别跟我提以往 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条回答
  • 2020-12-12 06:12

    3 if's and done :)

        if x % 2 == 0:
            print x
        if x == 237:
            break
        if x % 2 != 0: 
            continue
    

    Output

    402
    984
    360
    408
    980
    544
    390
    984
    592
    236
    942
    386
    462
    418
    344
    236
    566
    978
    328
    162
    758
    918
    
    0 讨论(0)
  • 2020-12-12 06:22

    Im just going throug this exercise in my "learning the basis thing" and i came out with a similar but somehow worse solution, patrik :(

    x = 0 for loop in numbers: if (numbers[x]) % 2 ==0: print (numbers[x]) x = x+1
    if (numbers[x]) ==237: break
    else: x =x+1 continue

    0 讨论(0)
  • 2020-12-12 06:29

    That's what else and elif are for:

    for x in numbers:
      if x == 237:
        break
      elif x % 2 == 0:
        print x
    
    0 讨论(0)
  • 2020-12-12 06:29

    This is also possible:

    try:
        i = numbers.index(237)
    except:
        i = len(numbers)
    for n in numbers[:i]:
        if not n%2:
           print n
    
    0 讨论(0)
  • 2020-12-12 06:34

    you can do that using list comprehension

    The solution would be like this:

    numbers = [x for ind,x in enumerate(numbers) if x % 2== 0 and numbers[ind+1]!=237 ]
    
    0 讨论(0)
  • 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

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