5
$\begingroup$

For a list of strings (or other elements):

SeedRandom[3]; t1 = Table[RandomChoice[CharacterRange["A", "E"]], 20] 
{"D", "A", "B", "C", "A", "A", "E", "C", "C", "C", "B", "A", "A", \ "C", "B", "D", "D", "A", "B", "C"} 

I want to split the list starting at a certain symbol (say "B"):

t2 = Split[t1, (#2 != "B") &] {{"D", "A"}, {"B", "C", "A", "A", "E", "C", "C", "C"}, {"B", "A", "A", "C"}, {"B", "D", "D", "A"}, {"B", "C"}} 

Now I define a function (so that I can further fork sublists starting at "C")

f[x_List, s_String] := Split[x, (#2 != s) &] f[#, "C"] & /@ t2 
{{{"D", "A"}}, {{"B"}, {"C", "A", "A", "E"}, {"C"}, {"C"}, {"C"}}, {{"B", "A", "A"}, {"C"}}, {{"B", "D", "D", "A"}}, {{"B"}, {"C"}}} 

To get the same output, the following works too:

Split[# , (#2 != "C") &] & /@ Split[t1, (#2 != "B") &] 

Question(s)

  1. seeking a better implementation of the pure function above or better still ...
  2. I want to write a function to which I can provide a main list such as t1 and a list of tokens {"B","C"} to achieve the same effect, perhaps using Fold that I can't figure out.

Thanks in advance for your help.

$\endgroup$

1 Answer 1

6
$\begingroup$

You could use "SplitBy" like the following:

SeedRandom[3]; t1 = Table[RandomChoice[CharacterRange["A", "E"]], 20] fl = 1; fun[c_] := (If[# == c, ++fl]; fl) & SplitBy[t1, {fun["B"], fun["C"]}] 

enter image description here

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.