Generating a list of EVEN numbers in Python

前端 未结 14 639
轻奢々
轻奢々 2021-01-17 15:48

Basically I need help in generating even numbers from a list that I have created in Python:

[1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597         


        
14条回答
  •  一向
    一向 (楼主)
    2021-01-17 16:08

    Just for fun, checking if number%2 != 1 also works ;)

    evens=[x for x in evens_and_odds if number%2 != 1 ]
    

    Note that you can do some clever things to separate out evens and odds in one loop:

    evens=[]
    odds=[]
    numbers=[ evens, odds ]
    for x in evens_and_odds:
        numbers[x%2 == 1].append(x)
    
    print evens
    print odds   
    

    The above trick works because logical expressions (==, >, etc.) operating on numbers True (1) and/or False (0).

提交回复
热议问题