7
$\begingroup$

I have a list like this one:

aaah= {{11, 21, 31}, {12, 22, 32}, {13, 23, 33}}

and I finally want to get a list which looks like this one:

{{{1, 11}, {1, 21}, {1, 31}}, 
 {{2, 12}, {2, 22}, {2, 32}}, 
 {{3, 13}, {3, 23}, {3, 33}}}

I am pretty sure that I can use Thread, List and Range to do this, but I can't get the right combination...

At the moment this is my best try:

Thread[List[Table[1, 3], aaah[[1]]]]

which does exactly what I want, but only on the first row. I appreciate any help! Thanks in advance

$\endgroup$
1

7 Answers 7

9
$\begingroup$

The easiest way to achieve this is with MapIndexed:

MapIndexed[
  {#2[[1]], #1} &,
  aaah,
  {2}
]

{{{1, 11}, {1, 21}, {1, 31}}, {{2, 12}, {2, 22}, {2, 32}}, {{3, 13}, {3, 23}, {3, 33}}}

$\endgroup$
1
  • $\begingroup$ An equivalent method: MapIndexed[ReplacePart[#2, 2 -> #1] &, {{11, 21, 31}, {12, 22, 32}, {13, 23, 33}}, {2}]. $\endgroup$ Jul 8, 2020 at 14:25
5
$\begingroup$
MapIndexed[Thread @ {First @ #2, #} &] @ aaah
{{{1, 11}, {1, 21}, {1, 31}},
{{2, 12}, {2, 22}, {2, 32}}, 
{{3, 13}, {3, 23}, {3, 33}}}
$\endgroup$
4
$\begingroup$

I think that the most natural way of doing this is by using MapIndexed. But if you want to use Range and Thread, this is one way:

{{11, 21, 31}, {12, 22, 32}, {13, 23, 33}} //
  {Length /* Range, Identity} //
  Through //
  Thread //
  Map[Thread]
$\endgroup$
4
$\begingroup$

Just for fun. Another options using Distribute:

MapIndexed[Distribute[{#2, #}, List] &]@aaah
$\endgroup$
3
$\begingroup$
Thread/@Transpose[{Range[3],aaah}]

{{{1, 11}, {1, 21}, {1, 31}}, {{2, 12}, {2, 22}, {2, 32}}, {{3, 13}, {3, 23}, {3, 33}}}

Or:

aaah//Thread/@Transpose[{Range@Length@#,#}]&

Or:

aaah//MapThread[Thread@*List,{Range@Length@#,#}]&
$\endgroup$
3
$\begingroup$
idxs = Range[3]
Thread /@ Thread[{idxs, aaah}]
$\endgroup$
1
$\begingroup$

You could use Thread, Range, Length, and Tranpose:

Thread[{Range[1, Length[aaah]], #}] & /@ Transpose[aaah] // Transpose

$\endgroup$

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.