4
$\begingroup$

I have two lists, list1 and list2. I want to Select from list1 using list2 as a comparison standard.

For example:

list1 = {1, 2, 3, 4, 5, 8}; 
list2 = {3, 5}; 
Select[list1, (#) < list2[[1]] &]

will give me elements in list1 that is smaller than the 1st element in list2. I want ot use Map to get lists of list, each containing sets of elements smaller than 1st, 2nd ..nth elemet of list2. Basically the results I want is the same as running

{Select[list1, (#) < list2[[1]] &], Select[list1, (#) < list2[[2]] &]}

but I want to use Map.Then I could not figure out how to get the slots to "find" its appropriate calling function. I was trying something like (Select[list1, #1 < #2 &]) /@ list2, but it was very obvious it won't work. Any suggestions?

$\endgroup$
  • 1
    $\begingroup$ Probably (16190) answers your question. $\endgroup$ – ybeltukov Feb 4 '15 at 22:06
4
$\begingroup$
Map[Function[a, Select[list1, (#) < a &]], list2]
$\endgroup$
3
$\begingroup$

Some random test set:

n = 1000;
list1 = RandomInteger[1000, n];
list2 = RandomInteger[1000, n];

You can select elements with Select and Fuction

res1 = Function[{x}, Select[list1, # < x &]] /@ list2; // AbsoluteTiming
(* {0.988713, Null} *)

There is similar function Cases, which looks better here

res2 = Cases[list1, x_ /; x < #] & /@ list2; // AbsoluteTiming
(* {1.004461, Null} *)

Your specific task can be done very fast by sorting lists

res3 = With[{s = Sort@list1}, s[[;; #]] & /@ 
       Pick[Accumulate@#, #, 0][[Ordering@Ordering@list2]] &@
     UnitStep[Ordering@Join[list2, list1] - Length@list2 - 1]]; // AbsoluteTiming
(* {0.008168, Null} *)

Sort /@ res1 == Sort /@ res2 == Sort /@ res3
(* True *)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.