6
$\begingroup$

Is there a way to split a list into sublists based on a pattern while keeping the matching value in the sublist?

For instance, we have the following list:

{a, x, x, a, b, y, a, c, z}

and we want to produce the following (split on a):

{{a, x, x}, {a, b, y}, {a, c, z}}

then how might we achieve this? In other words, we want to split a list based on a condition while keeping the condition in the sublist. So far I've tried SequenceSplit which produces the list without a (in this case). However, I'm having trouble formulating the pattern which will keep the split value in the sublist.

Thanks very much for your time!

$\endgroup$

3 Answers 3

7
$\begingroup$
alist = {a, x, x, a, b, y, a, c, z}

Split[alist, UnsameQ[#2, a] &]

{{a, x, x}, {a, b, y}, {a, c, z}}

$\endgroup$
8
$\begingroup$
SequenceCases[{a, x, x, a, b, y, a, c, z}, {a, Except[a] ..}]

{{a, x, x}, {a, b, y}, {a, c, z}}

$\endgroup$
2
$\begingroup$
list = {a, x, x, a, b, y, a, c, z};

Using SequenceSplit (new in 11.3)

SequenceSplit[list, p : {a, Except[a] ..} :> p]

{{a, x, x}, {a, b, y}, {a, c, z}}

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