Generating a list of EVEN numbers in Python

前端 未结 14 592
轻奢々
轻奢々 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:13

    You can do this with a list comprehension:

    evens = [n for n in numbers if n % 2 == 0]
    

    You can also use the filter function.

    evens = filter(lambda x: x % 2 == 0,numbers)
    

    If the list is very long it may be desirable to create something to iterate over the list rather than create a copy of half of it using ifilter from itertools:

    from itertools import ifilter
    evens = ifilter(lambda x: x % 2 == 0,numbers)
    

    Or by using a generator expression:

    evens = (n for n in numbers if n % 2 == 0)
    

提交回复
热议问题