Here's a mild improvement:
list = RandomInteger[{0, 9}, {50, 5}];
e1 = 1; e2 = 2;
Cases[list, {___, e1, ___, e2, ___} | {___, e2, ___, e1, ___}] // AbsoluteTiming
Select[list, MemberQ[#, e1] && MemberQ[#, e2] &] // AbsoluteTiming
{0.000227842, {{1, 2, 6, 5, 5}, {1, 9, 9, 1, 2}, {6, 1, 2, 8, 1}, {5,
2, 8, 2, 1}, {0, 0, 9, 1, 2}, {1, 2, 2, 4, 2}, {7, 7, 1, 9, 2}, {6,
0, 1, 2, 9}, {0, 0, 8, 2, 1}, {9, 5, 1, 2, 0}, {8, 1, 5, 2, 9}}}
{0.000355521, {{1, 2, 6, 5, 5}, {1, 9, 9, 1, 2}, {6, 1, 2, 8, 1}, {5,
2, 8, 2, 1}, {0, 0, 9, 1, 2}, {1, 2, 2, 4, 2}, {7, 7, 1, 9, 2}, {6,
0, 1, 2, 9}, {0, 0, 8, 2, 1}, {9, 5, 1, 2, 0}, {8, 1, 5, 2, 9}}}
Cases
, as you can see, is slightly faster. Sadly the improvement is less than a factor of two.
Here's a much faster solution:
list = RandomInteger[{0, 9}, {50000, 5}];
e1 = 1; e2 = 2;
Pick[list, Unitize@(Count[#, e1] Count[#, e2] & /@ list), 1]
(* output omitted *)
Comparisons:
Select[list, MemberQ[#, e1] && MemberQ[#, e2] &] //
AbsoluteTiming // First
Cases[list, {___, e1, ___, e2, ___} | {___, e2, ___, e1, ___}] //
AbsoluteTiming // First
Pick[list, Unitize@(Count[#, e1] Count[#, e2] & /@ list), 1] //
AbsoluteTiming // First
(* 0.252361 *)
(* 0.133419 *)
(* 0.0178847 *)
About 15 times faster than Select/MemberQ
.
The situation changes when I tried this with symbolic elements in the list:
Clear[a, b, c, d, e, f, g, h, i, j]
list = RandomChoice[{a, b, c, d, e, f, g, h, i, j}, {50000, 5}];
e1 = a; e2 = b;
Select[list, MemberQ[#, e1] && MemberQ[#, e2] &] //
AbsoluteTiming // First
Cases[list, {___, e1, ___, e2, ___} | {___, e2, ___, e1, ___}] //
AbsoluteTiming // First
Pick[list, Unitize@(Count[#, e1] Count[#, e2] & /@ list), 1] //
AbsoluteTiming // First
(* 0.158247 *)
(* 0.0228719 *)
(* 0.23266 *)
This time Cases
is the fastest.
list
one dimensional or are thel1,l2....
each lists themselves? $\endgroup$l1,l2,...
are lists as well $\endgroup$Cases
looks roughly twice as fast when using lists of lists of integers ande1
e2
also integers. $\endgroup$