Reputation: 17415
I just had an idea that I find pretty intriguing: A combination between map() and filter() using generator as predicate and yield from
. To make it short, here's the code:
def map_filter(function, iterable):
"""convert and filter a sequence"""
for i in iterable:
yield from function(i)
Now, what's the deal? Basically, this is a combination between the aforementioned two functions which incorporates both their functionality. Actually, the possibility to pass additional parameters to map()
is still missing, though that's a minor detail IMHO and it could be extended for that. Here's a comparison, generating squares of numbers:
def function(x):
return x * x
res = map(function, range(0, 10))
print(list(res))
def function(x):
yield x * x
res = map_filter(function, range(0, 10))
print(list(res))
Here's another, filtering odd numbers:
def function(x):
return x % 2 == 1
res = filter(function, range(0, 10))
print(list(res))
def function(x):
if x % 2 == 1:
yield x
res = map_filter(function, range(0, 10))
print(list(res))
And the last one, combining the two above:
def function1(x):
return x * x
def function2(x):
return x % 2 == 1
res = map(function1, filter(function2, range(0, 10)))
print(list(res))
def function(x):
if x % 2 == 1:
yield x * x
res = map_filter(function, range(0, 10))
print(list(res))
Notes and questions:
map_filter()
requires a generator (with yield
), so I can't use lambda
with it (Can I?). For very small filtering/mapping functions, the amount of code is larger therefore, but otherwise you can probably write more terse code using a combined filtering/mapping function.map_filter()
to remove elements from a sequence, but you can also use it to inject additional elements.Upvotes: 3
Views: 14936
Reputation: 385
Use list comprehensions with conditional instead. For example:
squared_evens = [n*n for n in range(10) if n % 2 == 0]
squared_evens
>>> [0, 4, 16, 36, 64]
Upvotes: 1
Reputation: 24133
You can define generator expressions:
>>> values = range(0, 10)
>>> evens = (value for value in values if not value % 2)
>>> even_squares = (even * even for even in evens)
>>> list(even_squares)
[0, 4, 16, 36, 64]
Upvotes: 5