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)
- seeking a better implementation of the pure function above or better still ...
- 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 usingFold
that I can't figure out.
Thanks in advance for your help.