Filter out sublist in Mathematica
rule-engine, wolfram-mathematica
Solution
This is a nice application for some/every:
some[f_, l_List] := (* whether f applied to some *)
Scan[If[f[#], Return[True]]&, l] === True (* element of list is True. *)
every[f_, l_List] := (* similarly, And @@ f/@l *)
Scan[If[!f[#], Return[False]]&, l]===Null (* (but with lazy evaluation). *)
So first make a function that checks a sublist for all zeroes/ones:
chk[lst_] := every[#==0||#==1&, lst]
Then filter your list-of-lists for sublists that pass the test:
Select[lst, chk]
Or, as a one-liner:
Select[lst, every[#==0||#==1&, #]&]
Problem
I am a newbie user in mathematica. Here is my problem: For example, I have a nested list: ``` lst = {{1, 0, 0}, {0, 1, 1}, {2, 0, 1}, {1}, {0,3}} ``` I want to only output those sublist whose elements are 0 or 1. The above list's output should be: ``` {{1, 0, 0}, {0, 1, 1}, {1}} ``` I can get the list that satisfies my conditions with this: ``` lst /. x:{(1 | 0) ..} :> x ``` But how can I get the converse of the pattern? like this: ``` lst /. x:NOT{(1 | 0) ..} :> Sequence[] ``` So that i can get the result in one stroke. thanks!