Generating a list of EVEN numbers in Python

点点圈 提交于 2020-01-14 07:30:07

问题


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, 2584, 4181, 6765, 10946, 17711, 28657, 46368, ...]

I have tried a couple different methods, but every time I print, there are odd numbers mixed in with the evens!

I know how to generate even/odd numbers if I were to do a range of 0-100, however, getting only the even numbers from the previous mentioned list has me stumped!

P.S. I've only been using python for a couple days, if this turns out to be extremely simple, thanks in advance!

EDIT: Thanks for all the replies, with your help I've gotten through this little problem. Here is what I ended up with to complete a little excercise asking to sum the even numbers of fibonacci sequence:

F = [1, 2]
while F[-1] < 4000000
    F.append(F[-1] + F[-2])

sum(F[1::3])
4613732

回答1:


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!




回答2:


The following sample should solve your problem.

Newlist = []
for x in numList:
   if x % 2 == 0:
      print x          
      Newlist.append(x)



回答3:


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]



回答4:


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)



回答5:


Just check this

A = [i for i in range(101)]
B = [x for x in A if x%2 == 0]
print B



回答6:


iterate through the list and use the modulo operator to check even

for number in list:
    if (number % 2) == 0: 
        ##EVEN



回答7:


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).




回答8:


You can use list comprehension to generate a new list that contains only the even members from your original list.

data = [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]

then:

new_data = [i for i in data if not i%2]

yields

[2, 8, 34, 144]

Or alternatively use a generator expression if you don't need all of the numbers at once:

new_data = (i for i in data if not i%2)

The values then would be availabe as needed, for instance if you used a for loop:

e.g.,

for val in new_data:
   print val

The advantage of the generator expression is that the whole list is not generated and stored in memory at once, but values are generated as you need them which makes less demand on memory. There are other important differences you might want to read up on at some point if you are interested.




回答9:


Instead of generating all Fibonacci numbers then filtering for evens, why not generate just the even values?

def even_fibs():
    a,b = 1,2
    while True:
        yield b
        a,b = a+2*b, 2*a+3*b

generates [2, 8, 34, 144, 610, 2584, 10946 ...]

then your sum code becomes:

total = 0
for f in even_fibs():
    if f >= 4000000:
        break
    else:
        total += f

or

from itertools import takewhile
total = sum(takewhile(lambda n: n<4000000, even_fibs()))



回答10:


You could do this using the filter function as follows:

F = [1, 2]
while F[-1] < 4000000:
    F.append(F[-1] + F[-2])
print(F)
print('\n')
#create the variable that could store the sorted values from the list you have created.
sorted_number=list(filter(lambda x:x%2==0,F))
print(sorted_number)



回答11:


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)



回答12:


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]




回答13:


Here are some of the different ways to get even numbers:

CASE 1 in this case, you have to provide a range

lst = []
for x in range(100):
    if x%2==0:
    lst.append(x)
print(lst)

CASE 2 this is a function and you have to pass a parameter to check if it is an even no or not def even(rangeno): for x in range(rangeno): if rangeno%2 == 0: return rangeno else: return 'No an Even No'

 even(2)

CASE 3 checking the values in the range of 100 to get even numbers through function with list comprehension

def even(no):
return [x for x in range(no) if x%2==0]

even(100)

CASE 4 This case checks the values in list and prints even numbers through lambda function. and this case is suitable for the above problem

lst = [2,3,5,6,7,345,67,4,6,8,9,43,6,78,45,45]
no = list(filter(lambda x: (x % 2 == 0), lst))
print(no)



回答14:


a = range(0,1000)
b = []
for c in a:
    if c%2==0:
        b.append(c)
print b


来源:https://stackoverflow.com/questions/11233355/generating-a-list-of-even-numbers-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!