Even numbers in Python

て烟熏妆下的殇ゞ 提交于 2019-12-02 22:40:24
SLaks

Range has three parameters.

You can write range(0, 10, 2).

Just use a step of 2:

range(start, end, step)

Try:

range( 0, 10, 2 )

I don't know if this is what you want to hear, but it's pretty trivial to filter out odd values with list comprehension.

evens = [x for x in range(100) if x%2 == 0]

or

evens = [x for x in range(100) if x&1 == 0]

You could also use the optional step size parameter for range to count up by 2.

>>> if 100 % 2 == 0 : print "even"
...
even

There are also a few ways to write a lazy, infinite iterators of even numbers.

We will use the itertools module and more_itertools1 to make iterators that emulate range().

import itertools as it

import more_itertools as mit


# Infinite iterators
a = it.count(0, 2)
b = mit.tabulate(lambda x: 2 * x, 0)
c = mit.iterate(lambda x: x + 2, 0)

All of the latter options can generate an infinite sequence of even numbers, 0, 2, 4, 6, ....

You can treat these like any generator by looping over them, or you can select n numbers from the sequence via itertools.islice or take from the itertools recipes e.g.:

mit.take(10, a)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

This is equivalent to list(range(0, 20, 2)). However, unlike range(), the iterator is paused and will yield the next batch of even numbers if run again:

mit.take(10, a)
# [20, 22, 24, 26, 28, 30, 32, 34, 36, 38]

Details

The options presented are all infinite iterators that start with an integer, i.e. 0.

  • a. itertools.count yields the next value incremented by a step=2 (see equivalent code).
  • b. more_itertools.tabulate is an itertools recipe that maps a function to each value of a number line (see source code).
  • c. more_itertools.iterate yields the starting value (0). It then applies a function to the last item (incrementing by 2), yields that result and repeats this process (see source code).

1A third-party package that implements many useful tools, including itertools recipes such as take and tabulate.

user3904440
#This is not suggestible way to code in Python, but it gives a better understanding


numbers = range(1,10)

even = []

for i in numbers:

     if i%2 == 0:

       even.append(i)
print (even)
Ray
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

b = [i for i in a if i % 2 == 0]

print("Original List -->", a,"\n")
print("and the Even Numbers-->", b)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!