Is filter/map equivalent to list comprehension?
Suppose I have the following function
def fib_gen():
a,b = 0,1
yield 0
yield 1
while True:
a,b = b,a+b
yield b
Now I can use list comprehension to list fib numbers:
a = fib_gen()
print [a.next() for i in range(int(sys.argv[1]))]
Suppose I want to list only even fib numbers. I would do the following with filter/map:
a = fib_gen()
print filter(even, map(lambda x: a.next(), range(int(sys.argv[1]))))
How can I get the same result with list comprehension?
You could use a generator to store the intermediate result, and “filter” on it.
or in one line:
Note that, if you want to take a definite number of elements from an iterator, you could use
itertools.isliceinstead: