9
$\begingroup$

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)?

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

3 Answers 3

5
$\begingroup$
k=2;
Map[#[[k]] &, dd, {2}]
 {{3, 10}, {76}}

Also

Flatten[dd, {3}][[k]]
 {{3, 10}, {76}}
$\endgroup$
1
$\begingroup$
dd = {{{12, 3, 5}, {14, 10, 11}}, {{15, 76, 65}}};

Using Query

First positions

Query[All, All, #[[1]] &] @ dd

{{12, 14}, {15}}

Middle positions

Query[All, All, #[[2]] &] @ dd

{{3, 10}, {76}}

$\endgroup$
1
$\begingroup$
dd = {{{12, 3, 5}, {14, 10, 11}}, {{15, 76, 65}}};

Using ReplaceAll for the first positions:

dd /. x_?VectorQ :> First@x

(*{{12, 14}, {15}}*)

Middle positions:

dd /. x_?VectorQ :> x[[-2]]

(*{{3, 10}, {76}}*)
$\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.