Filter out sublist in Mathematica
-
21-09-2019 - |
문제
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!
해결책
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&, #]&]
다른 팁
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) ..}]
제휴하지 않습니다 StackOverflow