Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set local variable in list comprehension?

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]  
like image 474
Hao Tan Avatar asked Oct 31 '14 10:10

Hao Tan


People also ask

Can you assign variables in list comprehension Python?

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.

Can you assign in list comprehension?

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.

Can we use while loop in list comprehension?

No, you cannot use while in a list comprehension.

Why list comprehension is faster than for loop?

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.


1 Answers

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]

like image 178
Lying Dog Avatar answered Sep 24 '22 00:09

Lying Dog