Skip to main content

pattern matching - Splitting a list



Please consider the following list:


data={1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3};

Now I would like to split the list into 0-sequences and Not-0-sequences as following:


{{1}, {0, 0, 0}, {2, 5, 2, 3}, {0, 0}, {3}}

All numbers are non-negative Integers, if that helps.



Answer



Split[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, Xor[#1 != 0, #2 == 0] &]


or more compactly


Split[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, Xnor[#1 == 0, #2 == 0] &]

works nicely here. Another way is:


SplitBy[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, Unitize]

or


SplitBy[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, Sign]

or, as Szabolcs suggests:



SplitBy[{1, 0, 0, 0, 2, 5, 2, 3, 0, 0, 3}, # == 0 &]

Comments