3
$\begingroup$

I want to turn the list

list1 = {{a},{b,c},{d,e,f,g}}

into

{ {{1,a}}, {{2,b},{2,c}}, {{3,d}, {3,e}, {3,f}, {3,g}} }

How can I do this? I've tried different forms of Map but none is working.

$\endgroup$
  • 4
    $\begingroup$ Maybe MapThread[Thread[{#2, #1}] &, {list1, Range[Length[list1]]}] or Thread[{#[[1]], #[[2]]}] & /@ Transpose[{Range[Length[list1]], list1} ? $\endgroup$ – b.gates.you.know.what Nov 21 '18 at 16:38
  • $\begingroup$ Perhaps Table[{ConstantArray[i, Length[list1[[i]]]], list1[[i]]}[Transpose], {i, 1, Length@list1}] $\endgroup$ – user11946 Nov 21 '18 at 16:51
  • $\begingroup$ Thanks, it's working! $\endgroup$ – AJHC Nov 21 '18 at 16:56
  • $\begingroup$ @b.gatessucks There is a bracket missing right at the end of your second solution. $\endgroup$ – Titus Nov 21 '18 at 17:05
  • $\begingroup$ Sorry - cut and paste didn't quite work for me in StackExchange - try this - Table[Transpose[{ConstantArray[i, Length[list1[[i]]]], list1[[i]]}], {i, 1, Length@list1}] $\endgroup$ – user11946 Nov 21 '18 at 18:25
1
$\begingroup$

Solutions by @b.gatessucks

MapThread[Thread[{#2, #1}] &, {list1, Range[Length[list1]]}]
(*or*)

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

I could not get @user11946's to work.

My own contribution is a generalisation.

The coordinates follow a geometric sequence: the first element is 1, the next two are 2, the next four are 4 etc. This can be tabulated as

list1 = {{a}, {b, c}, {d, e, f, g}}

bill = Table[
ConstantArray[i, 
FoldList[Times, 1, Table[2, Length[list1]]][[i]]], {i, 1, 
Length[list1]}]

In this thread I found many useful ways for element-wise Join in matrixes. I use one of them and define

threadJoin = Quiet[Re@##] /. Re -> List &;

threadJoin[bill, list1]

with the desired output. Most importantly, this is now marked as answered.

$\endgroup$
4
$\begingroup$
MapIndexed[Thread[{#2[[1]], #}] &, list1]

{{{1, a}}, {{2, b}, {2, c}}, {{3, d}, {3, e}, {3, f}, {3, g}}}

$\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.