this is a rather rudimentary question, but I was wondering if there are more efficient ways to do the following:

dd = {{{12, 3, 5}, {14, 10, 11}}, {{15, 76, 65}}}

If I have list dd, I want identify alternative ways to pick out elements in each sublist that are in the same positions and make them into a new list. For example, if I took out the first position of every sublist, I'd get the output:

Output={{12, 14}, {15}}

To make new output lists with the first/last element positions are the easiest and can be achieved through:

lis1 = Map[First, dd, {2}]
lis2 = Map[Last, dd, {2}]

However, to get an output where the "middle" position elements are taken and put into a new list ({{3, 10}, {76}}) I used:

lis3 = Map[Rest, dd, {2}]
lis4 = Map[First, lis3, {2}]

This seems like a rather roundabout way to obtain the desired list. Would there be a more streamlined alternative which I can Map directly to list dd and avoid having to manipulating the list first (lis3)?

  • $\begingroup$ Map[#[[k]]&, dd, {2}] with your choice of k? $\endgroup$
    – kglr
    Jun 29 '20 at 5:13
  • $\begingroup$ Or Apply[#k &, dd, {-2}], e.g., Apply[#2 &, dd, {-2}]. $\endgroup$ Jun 29 '20 at 5:59
  • 1
    $\begingroup$ Is dd[[ All, All, k ]] what you need or did I miss something? $\endgroup$
    – Kuba
    Jun 29 '20 at 8:22
  • $\begingroup$ dd/.{x_,y_,z_}:> y $\endgroup$
    – user1066
    Jun 29 '20 at 13:47
Map[#[[k]] &, dd, {2}]
 {{3, 10}, {76}}


Flatten[dd, {3}][[k]]
 {{3, 10}, {76}}

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.