2
$\begingroup$

The last of this series, an elaboration of a question from yesterday:

I'd like to go from:

startList = {"a-1","a","Z","c","d","e","f","g","Z","a","r","s","a-2",
"q","a","Z","c","d","e","f","a-2","m","Z","p","q","r"}

to:

endList = {{"a-1","a","Z","c","d"},{"a-1","g","Z","a","r"}, 
{"a-2","a","Z","c","d"},{"a-2","m","Z","p","q"}}

So, we make a sublist consisting of one element before "Z", "Z" itself, and the next two elements after each "Z". Then prefix "a-1" in front of each of these sublists, until "a-2" is encountered, at which point "a-2" is prefixed in front of each succeeding sublist, etc.

(The "a-1", "a-2", "a-3" etc. elements can be identified by StringContainsQ[element,"-"], none of the other string elements contain "-".)

Again thanks for your comments.

$\endgroup$

1 Answer 1

4
$\begingroup$
Join @@ (ReplaceList[# , {beg_, ___, a_, "Z", b_, c_, ___} :> 
  {beg, a, "Z", b, c}] & /@ Split[startList, StringFreeQ[#2, "-"] &])

{{"a-1", "a", "Z", "c", "d"}, {"a-1", "g", "Z", "a", "r"},
{"a-2", "a", "Z", "c", "d"}, {"a-2", "m", "Z", "p", "q"}}

Also:

ReplaceList[startList, {___, beg_?(Not[StringFreeQ[#, "-"]] &), 
 ___?(StringFreeQ[#, "-"] &),  a_, "Z", b_, c_, ___} :> {beg, a, "Z", b, c}]

{{"a-1", "a", "Z", "c", "d"}, {"a-1", "g", "Z", "a", "r"},
{"a-2", "a", "Z", "c", "d"}, {"a-2", "m", "Z", "p", "q"}}

$\endgroup$
1
  • $\begingroup$ Thank you, will study this! $\endgroup$
    – Suite401
    Dec 5, 2017 at 5:16

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.