问题
Does anyone know if Python has an in-built function to work to print out even values. Like range() for example.
Thanks
回答1:
Range has three parameters.
You can write range(0, 10, 2).
回答2:
Just use a step of 2:
range(start, end, step)
回答3:
Try:
range( 0, 10, 2 )
回答4:
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.
回答5:
>>> if 100 % 2 == 0 : print "even"
...
even
回答6:
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.countyields the next value incremented by astep=2(see equivalent code). - b.
more_itertools.tabulateis 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.
回答7:
#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)
回答8:
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)
来源:https://stackoverflow.com/questions/2184745/even-numbers-in-python