7
$\begingroup$

I would like to gather elements of a list separated by a delimiter ":"

lis = {"az", "2","b",":","7","b",":","7","c"} 

to make:

lis2 = {{az, 2,b},{7,b},{7,c}}

Thanks in advance for any direction...

$\endgroup$
2

3 Answers 3

8
$\begingroup$

This

is = {"az", "2", "b", ":", "7", "b", ":", "7", "c"};
DeleteCases[SplitBy[lis, # == ":" &], {":"}]

returns {{"az", "2", "b"}, {"7", "b"}, {"7", "c"}}

$\endgroup$
2
  • 2
    $\begingroup$ SameQ[] (===) is more suitable here than Equal[]. $\endgroup$ Jan 28, 2017 at 7:01
  • $\begingroup$ DeleteCases[SplitBy[lis, # === ":" &], {":"..}] would be better since this will also work if multiple separators occur in sequence. $\endgroup$ Nov 23, 2022 at 15:39
9
$\begingroup$

In 10th and later versions you can also use SequenceCases:

SequenceCases[lis, {a : Except[":"] ..} :> {a}]

{{"az", "2", "b"}, {"7", "b"}, {"7", "c"}}

Also:

Split[#, # =!= ":" &] /.  ":" | {":"} -> (## &[]) & @ lis

{{"az", "2", "b"}, {"7", "b"}, {"7", "c"}}

$\endgroup$
3
$\begingroup$

For the benefit of page visitors, this functionality was made available in 2018 through SequenceSplit.

enter image description here


lis = {"az", "2", "b", ":", "7", "b", ":", "7", "c"};
SequenceSplit[lis, {":"}]

{{"az", "2", "b"}, {"7", "b"}, {"7", "c"}}

$\endgroup$

Your Answer

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

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