[y for y in (mymap.get(x, None) for x in oldlist) if y]
Reference value of expression inside list comprehension in Python?
-
30-05-2022 - |
Question
If I have a list comprehension like
[mymap.get(x, None) for x in oldlist if mymap.get(x,None)]
Is there a way to do mymap.get(x,None)
only once here?
I imagine something like
[y for x in oldlist if mymap.get(x,None) as y]
but currently this is a SyntaxError
in py 2.x. I would like to be able to reference the resulting values of either the "expression" of list comprehension or from the "list_if" part of it.
I've also tried
[_ for x in oldlist if mymap.get(x,None)]
but that's a NameError
, I guess _
being only some interpreter feature on lines.
edit
Is there a way to reference this temporary/anonymous/unnamed variable somehow, without re-iterating the list?
Solution
OTHER TIPS
filter(None, (mymap.get(x, None) for x in oldlist))
or if it suits your fancy the equivalent code using bool
instead
filter(bool, (mymap.get(x, None) for x in oldlist))
And to answer your question, there's no way to reference the output function from the predicate.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow