How to transform {“Mon”, 1, 2, 3, 10, 100, “Tue”, 7, 11} to {{“Mon”,1,2,3,10,100}, {“Tue”,7, 11}} [duplicate]

This question already has an answer here:

Partition on sublists beginning with a certain marker elements

4 answers

Consider the following code snippet:

GroupBy[{“Mon”, 1, 2, 3, 10, 100, “Tue”, 7, 11}, MemberQ[{“Mon”, “Tue”}, #] &]

With output:

<|True -> {“Mon”, “Tue”}, False -> {1, 2, 3, 10, 100, 7, 11}|>

I expected however the following output:

<|"Mon" -> {1,2,3,10,100}, “Tue” -> {7, 11}|>

With the purpose of finally transforming this to

{{“Mon”,1,2,3,10,100}, {“Tue”,7, 11}}.

My question is really about how to transform lists like

{“Mon”, 1, 2, 3, 10, 100, “Tue”, 7, 11} to

{{“Mon”,1,2,3,10,100}, {“Tue”,7, 11}}.

and

{“Mon”, 1, “Tue”, 7, 11, “Sat”,6 } to

{{“Mon”,1}, {“Tue”,7, 11}, {“Sat”,6}}.

and so on ?

=================

=================

2 Answers
2

=================

Join @@@ Partition[
SplitBy[{“Mon”, 1, 2, 3, 10, 100, “Tue”, 7, 11}, MemberQ[{“Mon”, “Tue”}, #] &],2]

  

 

Generalize: Join @@@ Partition[SplitBy[list, Head@# == String &], 2]
– corey979
Sep 28 at 10:14

  

 

@corey979 Head@# == String & –> StringQ.
– Kuba
Sep 28 at 10:19

  

 

This one looks beautiful indeed @corey979
– nilo de roock
Sep 28 at 10:21

Might be done this way, using Internal`PartitionRagged to make arbitrary partitions

ls = {“Mon”, 1, 2, 3, 10, 100, “Tue”, 7, 11}

diff = Differences@Flatten@Join[Position[Head /@ ls, String], {{Length@ls + 1}}]
Internal`PartitionRagged[ls, diff]

{{“Mon”, 1, 2, 3, 10, 100}, {“Tue”, 7, 11}}