Filtering list from a list

I have two lists: one containing a list of tuples (numbers) and the other the list of numbers. For instance, L = [(2,3),(5,6), (4,6),…] and E = [2,5,7,3…]. Now, are there any other better ways to do similar to the following?

V = [filter(x->x[1]== e, L) for e in E]

Thanks in advance.

1 Like

The desired result is not well defined in your example. Your version produces empty tuples or doubled entries in the result depending on values in L and E.
Here are two variants:

filter( x -> x[1] in E, L)

But depending on you data and size this may be much slower as your version.
If E can be sorted there is also:

filter( x -> insorted(x[1],E), L)

which will be much faster if E is sorted.

The best solution depends on what you really want as a result and the sizes of L and E.

2 Likes
using SplitApplyCombine

group(t->first(t) ∈ Set(E), L)[true]

#or

groupview(t->first(t) ∈ Set(E) ,L)[true]


#or

[e for e in L if first(e) ∈ Set(E)]
4 Likes
using SplitApplyCombine

(D -> [haskey(D,e) ? D[e] : similar(L,0) for e in E])(group(first, L))

gives exactly same result as OP (thanks to cute group function @rocco_sprmnt21 mentioned).

Yeah, it looks worse than OP expression, but possibly lower time complexity (and higher space complexity).

1 Like

You can use filter directly like this. There is no need for comprehension.

L = [(2,3), (5,6), (4,6)]; 
E = [2,5,7,3];

filter(x->first(x) in E, L)
2-element Vector{Tuple{Int64, Int64}}:
 (2, 3)
 (5, 6)
3 Likes