4
$\begingroup$

Let us consider the following type of data list

data = {{0.35, 0.2}, {-0.0700506}, {-1.04149}, {0.52, 0.2}, {-0.0100506}, {-1.02149}, {0.593423},
        {0.75, 0.2}, {0.0700506}, {1.04149}, {-0.193423}, {-0.834902}}

We see that first, we have a sub-list guide with two elements {a, b}, then we have single elements {c} and then new sub-list guides.

I want the following: create a new list containing the first element of each guide sub-list along with all the following single elements. In our case, we should have the following output

data2 = {{0.35, -0.0700506}, {0.35, -1.04149}, {0.52, -0.0100506}, {0.52, -1.02149}, 
         {0.52, 0.593423}, {0.75, 0.0700506}, {0.75, 1.04149}, {0.75, -0.193423}, {0.75, -0.834902}}

Any suggestions?

$\endgroup$
2
  • $\begingroup$ Is the second element of {a, b} always going to be 0.2, or at least the same across al sublists? $\endgroup$ – MarcoB Apr 1 at 19:01
  • $\begingroup$ @MarcoB No, it won't be always the same, but we do not care about the second element.. $\endgroup$ – Vaggelis_Z Apr 1 at 19:08
7
$\begingroup$
SequenceCases[data, {a : {_, _}, b : {_} ..} :>
    (Sequence @@ ({a[[1]], #} & /@ Flatten[{b}]))]
{{0.35, -0.0700506}, {0.35, -1.04149}, {0.52, -0.0100506},
 {0.52, -1.02149}, {0.52, 0.593423}, {0.75, 0.0700506},
 {0.75, 1.04149}, {0.75, -0.193423}, {0.75, -0.834902}}

Alternatively, Split and post-process:

Join @@ Map[Thread[{First @ #, Rest @ #}] &] @ 
   Split[data, Length[#2] == 1 &][[All, All, 1]]
 same result
$\endgroup$
2
  • $\begingroup$ It works well! Just a comment: in cases where the original data list contains too many elements, the procedure of obtaining the new list is very time-consuming (several minutes of CPU time). Is there a way to speed us the process? $\endgroup$ – Vaggelis_Z Apr 1 at 21:13
  • $\begingroup$ @Vaggelis_Z, the updated version of the second method is slightly faster. $\endgroup$ – kglr Apr 1 at 21:44

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.