3
$\begingroup$

I am trying to make a function that effects the operation:

{ a1, a2, ..., an } -> { {1, {a1}}, {2, {a2}}, ..., {n, {an}} } 

I have defined my function to be:

x10 := MapThread[List, {{x6}, {list10}}, 1]
x6 = Range[Length[list10]]
list10 = {a, b, c, d, e}
Print[x10]

which gives the output:

{{{1,2,3,4,5},{a,b,c,d,e}}}

I think I might need to use the attribute HoldAll, but is anything else necessary to get the required output?

$\endgroup$
2
  • $\begingroup$ Make a standalone MapThread with your input explicitly inside and make sure your curly brackets are ok. $\endgroup$
    – Kuba
    Oct 29, 2018 at 13:21
  • $\begingroup$ In both an after-the-fact and FWIW vein: Transpose[Flatten[x10, 1]] yields {{1, a}, {2, b}, {3, c}, {4, d}, {5, e}} $\endgroup$
    – Rabbit
    Jan 23, 2019 at 4:20

2 Answers 2

3
$\begingroup$
x10 := MapThread[List, {x6, List /@ list10}]
x6 := Range[Length[list10]]
list10 = {a, b, c, d, e}
x10

{{1, {a}}, {2, {b}}, {3, {c}}, {4, {d}}, {5, {e}}}

n = 5;
lst = Array[Symbol["a" <> ToString@#] &, n];
MapIndexed[{#2[[1]], {#}} &, lst]

{{1, {a1}}, {2, {a2}}, {3, {a3}}, {4, {a4}}, {5, {a5}}}

Also

MapIndexed[{#2[[1]], #} &, List /@ lst]
MapIndexed[{#2.{1}, {#}} &, lst] (* thanks: Mr.Wizard *)
MapThread[List, {Range@n, List /@ lst}]
Thread[{Range @ n, List /@ lst}]

{{1, {a1}}, {2, {a2}}, {3, {a3}}, {4, {a4}}, {5, {a5}}}

$\endgroup$
2
  • $\begingroup$ How about MapIndexed[{#2.{1}, {#}} &, lst] $\endgroup$
    – Mr.Wizard
    Oct 29, 2018 at 16:26
  • $\begingroup$ @Mr.Wizard, that too works. Thank you. $\endgroup$
    – kglr
    Oct 29, 2018 at 16:32
2
$\begingroup$

I would use something from the Replace family to tackle this, i.e.

i = 1;
Replace[{a, b, c, d, e, f, g}, x_ :> {i++, {x}}, 1]

{{1, {a}}, {2, {b}}, {3, {c}}, {4, {d}}, {5, {e}}, {6, {f}}, {7, {g}}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.