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...
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityI 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...
This
is = {"az", "2", "b", ":", "7", "b", ":", "7", "c"};
DeleteCases[SplitBy[lis, # == ":" &], {":"}]
returns {{"az", "2", "b"}, {"7", "b"}, {"7", "c"}}
SameQ[]
(===
) is more suitable here than Equal[]
.
$\endgroup$
Jan 28, 2017 at 7:01
DeleteCases[SplitBy[lis, # === ":" &], {":"..}]
would be better since this will also work if multiple separators occur in sequence.
$\endgroup$
Nov 23, 2022 at 15:39
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"}}
For the benefit of page visitors, this functionality was made available in 2018 through SequenceSplit
.
lis = {"az", "2", "b", ":", "7", "b", ":", "7", "c"};
SequenceSplit[lis, {":"}]
{{"az", "2", "b"}, {"7", "b"}, {"7", "c"}}