1
$\begingroup$

I need to generate conditionals (||, &&, etc) from a list conditionList that I don't know beforehand how many/which elements will it contain.

For simplicity, let's consider integers:

conditionList = {3,5};

So, taking this list, I'd like to generate the conditionals to filter some other list. For instance:

listToBeFiltered={1,2,3,4,5,6,7,8,9};

Select[listToBeFiltered, (# == 3 || # == 5) &]

Here I manually made the argument (# == 3 || # == 5) for Select. How could I have generated it from conditionList directly?

My first guess was to generate the conditions as strings, and then use ToExpression to apply it to Select, but this does not work:

myConditions = 
 StringDrop[
  StringJoin[
   Table[StringJoin["#==", IntegerString[conditionList[[a]]], 
     "||"], {a, 1, Length[conditionList]}]], -2]

Gives:

#==3||#==5

Which when applied gives an empty list:

Select[listToBeFiltered, (ToExpression@myConditions) &]

{}

Thanks!

$\endgroup$
  • 6
    $\begingroup$ Select[listToBeFiltered, MemberQ[conditionList, #] &] $\endgroup$ – Bob Hanlon Jul 4 at 6:01
  • 3
    $\begingroup$ Cases[ listToBeFiletered, Alternatives@@conditionList ] $\endgroup$ – LouisB Jul 4 at 7:19

Browse other questions tagged or ask your own question.