I have a method that takes a list and returns an object:
# input a list, returns an object def map_to_obj(lst): a_list = f(lst) return a_list[0] if a_list else None
I want to get a list that contains all the mapped elements that aren't None
.
Like this:
v_list = [v1, v2, v3, v4] [map_to_obj(v) for v in v_list if map_to_obj(v)]
But it doesn't seem good to call the map_to_obj
method twice in the list comprehension.
Is there a way to have local variables in list comprehensions so that it can have better performance?
Or does the compiler optimize it automatically?
Here is what I want:
(sml like) [let mapped = map_to_obj(v) in for v in v_list if mapped end]
You can't assign a variable in a comprehension, but you can use a nested generator expression, which does what I think you want (without a lambda function). Show activity on this post. You can't do that. Assignment is always a statement in Python; list comprehensions can only contain expressions.
Using Assignment Expressions in List Comprehensions. We can also use assignment expressions in list comprehensions. List comprehensions allow you to build lists succinctly by iterating over a sequence and potentially adding elements to the list that satisfy some condition.
No, you cannot use while in a list comprehension.
List comprehensions are faster than for loops to create lists. But, this is because we are creating a list by appending new elements to it at each iteration.
Use nested list comprehension:
[x for x in [map_to_obj(v) for v in v_list] if x]
or better still, a list comprehension around a generator expression:
[x for x in (map_to_obj(v) for v in v_list) if x]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With