简体   繁体   中英

Even numbers in Python

Does anyone know if Python has an in-built function to work to print out even values. Like range() for example.

Thanks

Range has three parameters.

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

只需使用步骤 2:

range(start, end, step)

尝试:

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
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_itertools 1 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 eg:

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

1 A 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM