开发者

Even numbers in Python

开发者 https://www.devze.com 2022-12-18 16:00 出处:网络
Does anyone know if Python has an in-built function to work t开发者_如何学Co print out even values. Like range() for example.

Does anyone know if Python has an in-built function to work t开发者_如何学Co print out even values. Like range() for example.

Thanks


Range has three parameters.

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


Just use a step of 2:

range(start, end, step)


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.


Try:

range( 0, 10, 2 )


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


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)


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.


#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)
0

精彩评论

暂无评论...
验证码 换一张
取 消