3

I have a list:

oldList = {"a-1", "b", "c", "a-2", "d", "e", "f", "a-3", "w"}

and would like to get the following list:

newList = {{a-1,b}, {a-1,c}, {a-2,d}, {a-2,e}, {a-2,f}, {a-3,w}}

I see that there was a similar but not identical question was posed here four years ago. I started by using StringMatchQ and Position to find the position of the elements that contain "-" and then Complement to find which elements need to have the terms containing "-" affixed to them. But Insert doesn't seem to be very flexible and I'd like to avoid a bunch of For loops.

kglr
  • 394,356
  • 18
  • 477
  • 896
Suite401
  • 4,793
  • 8
  • 18

2 Answers2

7
Join @@ (Thread[{#, {##2}}] & @@@ Split[oldList, StringFreeQ[#2, "a"] &]) 

{{"a-1", "b"}, {"a-1", "c"}, {"a-2", "d"}, {"a-2", "e"}, {"a-2", "f"}, {"a-3", "w"}}

Also,

Flatten[Thread[{#, {##2}}] & @@@ Split[oldList, StringFreeQ[#2, "a"] &], 1]

{{"a-1", "b"}, {"a-1", "c"}, {"a-2", "d"}, {"a-2", "e"}, {"a-2", "f"}, {"a-3", "w"}}

kglr
  • 394,356
  • 18
  • 477
  • 896
  • My mistake, I should have made it clear that oldList is a list of strings. Both of your solutions lead to {{"a-1", "b"}, {"a-1", "c"}, {"a-1", "a-2"}, {"a-1", "d"}, {"a-1", "e"}, {"a-1", "f"}, {"a-1", "a-3"}, {"a-1", "h"}, {"a-1", "w"}, {"a-1", "z"}} – Suite401 Dec 04 '17 at 04:11
  • @Suite401, please see the updated version. – kglr Dec 04 '17 at 05:06
  • Yes. Thanks /@you, kglr, swish. – Suite401 Dec 04 '17 at 05:23
  • And one final generalization question, and i'll let go of this issue; – Suite401 Dec 04 '17 at 06:34
  • I will post it as a new question, and please tell me what the best way to handle these situations, so as not to annoy people. – Suite401 Dec 04 '17 at 06:44
6

Try this:

Flatten[
  SequenceCases[oldList,
      {left:_Plus,right:Except[_Plus]..}:>Thread[{left,{right}}]]
, 1]
swish
  • 7,881
  • 26
  • 48