8

I've got data of the type:

list = {"Class","MW","10 - 11"}

which I would like to split into a number of lists based on the number of characters in the second list element. In the above case, the desired output would be:

newlists = {{"Class","M","10-11"},{"Class","W","10-11"}}

StringSplit[list[[2]],""] gets me in the right direction (the string I want to split will always be in the same position in the list); however, I don't know how to thread this new sublist through the original list.

bobthechemist
  • 19,693
  • 4
  • 52
  • 138

5 Answers5

11

Here's how you can thread them:

newlists = Thread[{#, Characters@#2, ##3}] & @@ list
(* {{"Class", "M", "10 - 11"}, {"Class", "W", "10 - 11"}} *)
rm -rf
  • 88,781
  • 21
  • 293
  • 472
  • Is there a less ambiguous way to map this command over a list of list: Thread[{#, Characters@#2, ##3}]& @@ # & /@ multilists? I don't know how concerned I should be about nested pure functions. – bobthechemist Oct 02 '13 at 18:02
  • 1
    @bobthechemist Thread[{#, Characters@#2, ##3}] & @@@ multilists you can also add // Flatten[#, 1] & if you need. – Kuba Oct 02 '13 at 19:08
7

Here is an approach that doesn't use threading.

data = {"Class", "MW", "10 - 11"};
{a, b, c} = data;
new = {a, #, c} & /@ Characters @ b
{{"Class", "M", "10 - 11"}, {"Class", "W", "10 - 11"}}
m_goldberg
  • 107,779
  • 16
  • 103
  • 257
3
Distribute[MapAt[Characters, list, {2}], List] (* or *)
Distribute[MapAt[StringSplit[#, ""]&, list, {2}], List]

{{"Class", "M", "10 - 11"}, {"Class", "W", "10 - 11"}}

kglr
  • 394,356
  • 18
  • 477
  • 896
2

Maybe not handy but interesting way to apply automatic threading:

SetAttributes[h, Listable];
h @@ MapAt[Characters, list, {2}] /. h -> List
{{"Class", "M", "10 - 11"}, {"Class", "W", "10 - 11"}}
multilist = {{"Class", "MW", "10 - 11"}, {"Class", "MK", "10 - 11"}}

h @@@ MapAt[Characters, multilist, {All, 2}] /. h -> List
{{{"Class", "M", "10 - 11"}, {"Class", "W", "10 - 11"}}, 
   {{"Class", "M", "10 - 11"}, {"Class", "K", "10 - 11"}}}
Kuba
  • 136,707
  • 13
  • 279
  • 740
2
fun[u_] := Module[{dow},
  dow = Characters[#[[2]]] &@u;
  ReplacePart[u, 2 -> #] & /@ dow]
ubpdqn
  • 60,617
  • 3
  • 59
  • 148