6
$\begingroup$

I am trying to split a list when there is an empty row. I have tried the following:

a = {{1, 1, 1}, {2, 2, 2}, {, ,}, {3, 3, 3}};
b = Split[a, # == Null]

but my result is:

{{{1, 1, 1}}, {{2, 2, 2}}, {{Null, Null, Null}}, {{3, 3, 3}}}

which is not correctly split.

I would like to have {1,..} and {2,...} gathered together:

{{{1, 1, 1}, {2, 2, 2}}, {{Null, Null, Null}}, {{3, 3, 3}}}
$\endgroup$
2
  • 2
    $\begingroup$ A pure function needs to end with &: b = Split[a, # == Null &] $\endgroup$
    – Bob Hanlon
    Commented Aug 2, 2016 at 14:40
  • $\begingroup$ Related (6727) $\endgroup$
    – Mr.Wizard
    Commented Aug 2, 2016 at 15:03

3 Answers 3

7
$\begingroup$

Read carefully documentation of Split, you need its friend SplitBy:

SplitBy[a, MemberQ[Null]]

{{{1, 1, 1}, {2, 2, 2}}, {{Null, Null, Null}}, {{3, 3, 3}}}

$\endgroup$
0
3
$\begingroup$

Here's one way:

Split[{{1, 1, 1}, {2, 2, 2}, {, ,}, {3, 3, 3}},
      ! (MatchQ[#1, {Null ..}] || MatchQ[#2, {Null ..}]) &]
$\endgroup$
1
  • $\begingroup$ Awesome !! That's what I was looking for! Thank you! $\endgroup$
    – henry
    Commented Aug 2, 2016 at 14:41
3
$\begingroup$

Here two ways to do it using Split.

a = {{1, 1, 1}, {2, 2, 2}, {, ,}, {3, 3, 3}, {4, 4, 4}};

With[{p1 = {{_Integer ..} ..}}, Split[a, MatchQ[{#1, #2}, p1] &]
With[{p2 = {{Except[Null] ..} ..}}, Split[a, MatchQ[{#1, #2}, p2] &]]]

Both give

{{{1, 1, 1}, {2, 2, 2}}, {{Null, Null, Null}}, {{3, 3, 3}, {4, 4, 4}}}

The form using pattern p2 is probably better because it is more general. It will handle

c = {{1, 1, 1}, {2, 2, 2}, { , ,}, {x, y, z}, {4, 4, 4}};

correctly, while the form using p1 stumbles on the sub-list {x, y, z}.

With[{p1 = {{Except[Null] ..} ..}}, Split[c, MatchQ[{#1, #2}, p1] &]]

{{{1, 1, 1}, {2, 2, 2}}, {{Null, Null, Null}}, {{x, y, z}, {4, 4, 4}}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.