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$

2 Answers 2

6
$\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$
7
$\begingroup$
SequenceCases[{a, x, x, a, b, y, a, c, z}, {a, Except[a] ..}]

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

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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