4
$\begingroup$

I have this list,

  {{a}, {i1, i2, i3}, {1, 2, 3}}

which I want to rearrange to this:

  {{1, i1, a}, {2, i2, a}, {3, i3, a}}

It is for use with ListPlot3D[]. How can I do it?

$\endgroup$
4
  • 4
    $\begingroup$ Transpose@Reverse[PadRight[#, 3, a] & /@ list] $\endgroup$ – Bob Hanlon May 27 at 2:49
  • $\begingroup$ @BobHanlon That will work on the OP's MWE (at least I assume it's an MWE...), but not on longer examples, e.g., list={{a}, {i1, i2, i3, i4}, {1, 2, 3, 4}}. $\endgroup$ – theorist May 27 at 5:41
  • 1
    $\begingroup$ @theorist - more generally, Transpose@ Reverse[PadRight[#, Length[list[[-1]]], list[[1, 1]]] & /@ list] $\endgroup$ – Bob Hanlon May 27 at 5:56
  • 1
    $\begingroup$ @BobHanlon Another approach using padding: ArrayPad[Thread@Reverse@Rest@list, {{0}, {0, 1}}, First@list] $\endgroup$ – theorist May 27 at 6:05
5
$\begingroup$

A crappy attempt:

{{a}, {i1, i2, i3}, {1, 2, 3}} /. {a_, b_, c_} :> 
   Thread[List[c, b, x]] /. x :> a
$\endgroup$
3
  • $\begingroup$ Could you please tell me what this symbol ( :> ) is? I couldn't find it $\endgroup$ – Delaram Nematollahi May 27 at 17:20
  • $\begingroup$ @DelaramNematollahi See here: Rule Delayed $\endgroup$ – infinitezero May 27 at 18:21
  • $\begingroup$ @Charmbracelet Thank you $\endgroup$ – Delaram Nematollahi May 27 at 19:05
7
$\begingroup$
Thread[{#3,#2,Sequence@@#1}]&@@lst

{{1, i1, a}, {2, i2, a}, {3, i3, a}}

Slightly shorter

Thread[{#3,#2,First@#1}]&@@lst
$\endgroup$
5
$\begingroup$
list = {{a}, {i1, i2, i3}, {1, 2, 3}} 
#~Join~First@list& /@Thread@Reverse@Rest@list
$\endgroup$
4
$\begingroup$
f = Thread @ Reverse @ PadRight[#, Automatic, #] &;

Examples:

lst1 = {{a}, {i1, i2, i3}, {1, 2, 3}};

f @ lst1
 {{1, i1, a}, {2, i2, a}, {3, i3, a}}
lst2 = {{a}, {i1, i2, i3}, {x, y}, {1, 2, 3, 4}};

f @ lst2
 {{1, x, i1, a}, {2, y, i2, a}, {3, x, i3, a}, {4, y, i1, a}}
$\endgroup$
1
  • 1
    $\begingroup$ I think Transpose is a little more natural/accessible here than Thread. $\endgroup$ – Greg Martin May 28 at 7:00

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.