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.

  • 4
    $\begingroup$ Don't you think you could modify answers to your previous questions to apply them here? $\endgroup$ – jjc385 Dec 4 '17 at 4:47
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"}}


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"}}

  • $\begingroup$ 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"}} $\endgroup$ – Suite401 Dec 4 '17 at 4:11
  • $\begingroup$ @Suite401, please see the updated version. $\endgroup$ – kglr Dec 4 '17 at 5:06
  • $\begingroup$ Yes. Thanks /@you, kglr, swish. $\endgroup$ – Suite401 Dec 4 '17 at 5:23
  • $\begingroup$ And one final generalization question, and i'll let go of this issue; $\endgroup$ – Suite401 Dec 4 '17 at 6:34
  • $\begingroup$ 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. $\endgroup$ – Suite401 Dec 4 '17 at 6:44

Try this:

, 1]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.