Suppose we have a generator expression, perhaps a simple one, but not necessarily so:
(function(x) for x in values)
What is the preferred way to filter the values generated by this generator expression? I.e. we don't want to filter on the value of x, but on the value of function(x)?
Of course
# this only filters on the inputs to the function, not on its results
(function(x) for x in values if _some_condition_expr_)
I presume that the following would be most pythonic (incidentally also getting rid of the generator expression itself):
_ = lambda x: x # simple filter for truthy values
filter(_, map(function, values)) # <<< is this the best we can do?
# or
filter(_, (generator_expression_contents_here))
- as opposed to this abomination:
(y for y in (function(x) for x in values) if y)
Is there something I'm missing in generator expressions that would allow filtering the result without nesting expressions etc.? In other words, is the filter(map()) approach the best we can do? I'm not trying to find something esoteric, just making sure that I'm not missing some cleaner or more Pythonic way of doing it.
AFAIK, Python doesn't come with an identity function (_ above), nor with an is_true function.