Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter out sublist in Mathematica

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!

like image 878
jscoot Avatar asked Dec 22 '22 09:12

jscoot


1 Answers

Starting with:

lst = {{1, 0, 0}, {0, 1, 1}, {2, 0, 1}, {1}, {0, 3}};

You can filter with this:

Cases[lst, {(1 | 0) ..}]

Or get the complement with either:

Cases[lst, Except @ {(1 | 0) ..} ]

or:

DeleteCases[lst, {(1 | 0) ..}]
like image 174
Mr.Wizard Avatar answered Dec 29 '22 20:12

Mr.Wizard