Generating a list of EVEN numbers in Python

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

    You could use a for and if loop using the length function, like this:

    for x in range(len(numList)):
        if x%2 == 0:
            print(x)
            NewList.append(x)
    
    0 讨论(0)
  • 2021-01-17 16:06

    Basically you should create a variable and put your list in and then sort your even numbers list by adding it only the even numbers

    numbers = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, ...] even = [e for e in numbers if e%2==0]

    0 讨论(0)
  • 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).

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-17 16:16

    Use a list comprehension (see: Searching a list of objects in Python)

    myList = [<your list>]
    evensList = [x for x in myList if x % 2 == 0]
    

    This is good because it leaves list intact, and you can work with evensList as a normal list object.

    Hope this helps!

    0 讨论(0)
  • 2021-01-17 16:16

    In your specific case my_list[1::3] will work. There are always two odd integers between even integers in fibonacci: even, odd, odd, even, odd, odd.....

    >>> my_list = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368]
    >>>         
    ... 
    >>> my_list[1::3]
    [2, 8, 34, 144, 610, 2584, 10946, 46368]
    
    0 讨论(0)
提交回复
热议问题