2
$\begingroup$

I have a data set that looks like this:

lis = {a,{{b,c},{d,e}},m,{p,q}}

Each single element of the list ("a" and "m" in this example) is followed by one or more sublists consisting of two elements ("{b,c}", "{d,e}" and "{p,q}" in this example). I would like to tag each sublist pair with its preceding single element, turning the list into:

lis2 = {{b,c,a},{d,e,a},{p,q,m}}

I would be interested in an efficient way of doing this, and thank you in advance for any ideas.

$\endgroup$
3
$\begingroup$

Split with a custom test is the first thing that comes to mind. And then Map to assemble the results.

lis = {a, {{b, c}, {d, e}}, m, {p, q}};
splitlis = Split[lis, Not[ListQ[#1]] && ListQ[#2] &];
mapfun[{x_, y_}] := Map[Append[#, x] &, Partition[Flatten[y], 2]];
Flatten[Map[mapfun, splitlis], 1]

(* {{b, c, a}, {d, e, a}, {p, q, m}} *)

$\endgroup$
  • $\begingroup$ There's nothing in the question to suggest that the initial split couldn't just be Partition[lis, 2]. $\endgroup$ – wxffles Nov 2 '16 at 3:30
  • $\begingroup$ Works like a charm. Thanks! $\endgroup$ – Suite401 Nov 2 '16 at 5:30

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.