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!
Select[listToBeFiltered, MemberQ[conditionList, #] &]– Bob Hanlon Jul 04 '20 at 06:01Cases[ listToBeFiletered, Alternatives@@conditionList ]– LouisB Jul 04 '20 at 07:19