7
$\begingroup$

Given a list

lst={0,0,0,0,0,"A1",0,0,0,"B2",0,0,"C3","D4","E5",0,0,0,"F6"}

how can I split it as

{{0,0,0,0,0},{"A1",0,0,0},{"B2",0,0},{"C3"},{"D4"},{"E5",0,0,0},{"F6"}}

I want to use SequenceSplit, but I don't know how to set up the right pattern.

SequenceSplit[lst, {_String} -> {}]
$\endgroup$

3 Answers 3

6
$\begingroup$
Split[lst, Not @ StringQ @ #2 &]

{{0, 0, 0, 0, 0}, {"A1", 0, 0, 0}, {"B2", 0, 0}, {"C3"}, {"D4"}, {"E5", 0, 0, 0}, {"F6"}}

SequenceSplit[lst, {s_String, a : Except[_String] ...} :> {s, a}]

{{0, 0, 0, 0, 0}, {"A1", 0, 0, 0}, {"B2", 0, 0}, {"C3"}, {"D4"}, {"E5", 0, 0, 0}, {"F6"}}

$\endgroup$
8
  • $\begingroup$ Very nice,Thanks! what do #1 and #2 mean in Split function? $\endgroup$
    – Jerry
    Commented Jan 13, 2019 at 3:49
  • 2
    $\begingroup$ @Jerry see Working with Pure Functions and Slot $\endgroup$
    – Mr.Wizard
    Commented Jan 13, 2019 at 3:56
  • $\begingroup$ kglr, do you have something against !? :^) $\endgroup$
    – Mr.Wizard
    Commented Jan 13, 2019 at 3:57
  • $\begingroup$ @Mr.Wizard, thank you. $\endgroup$
    – kglr
    Commented Jan 13, 2019 at 4:01
  • 2
    $\begingroup$ @Jerry, in a test function used as the second argument of Split, #1 refers to the first element of a consecutive pair and #2 to the second, See also animation - Split which illustrates how it works for the default test function SameQ. $\endgroup$
    – kglr
    Commented Jan 13, 2019 at 4:04
2
$\begingroup$
list = 
 {0, 0, 0, 0, 0, "A1", 0, 0, 0, "B2", 0, 0, "C3", "D4", "E5", 0, 0, 0, "F6"};

SequenceSplit[list, x : {_, 0 ...} :> x]

{{0, 0, 0, 0, 0}, {"A1", 0, 0, 0}, {"B2", 0, 0}, {"C3"}, {"D4"}, {"E5", 0, 0, 0}, {"F6"}}

$\endgroup$
1
$\begingroup$
list = {0, 0, 0, 0, 0, "A1", 0, 0, 0, "B2", 0, 0, "C3", "D4", "E5", 0, 0, 0, "F6"};

An alternative is to use SequenceCases:

patts = {s_String, a : Except[_String] ...} | {a : Except[_String] ..} :> {s, a};

SequenceCases[lst, patts]

{{0, 0, 0, 0, 0}, {"A1", 0, 0, 0}, {"B2", 0, 0}, {"C3"}, {"D4"}, {"E5", 0, 0, 0}, {"F6"}}

$\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.