TransWikia.com

First elements in sublists

Mathematica Asked on March 19, 2021

Given

t1 = {{{1, 2, 3, 4}, {5, 6, {15, 16}, 7}}, {11, 12, 13, 14}};

I try to get First elements from sublists which would yield

{1,5,15,11}

How to use First, Take or #1 for this problem?

4 Answers

If preserving the "order" of extracted elements matters, you can use

ClearAll[fa, fb]

fa = Cases[ReplaceRepeated[{a : Except[_List], b__} :> {{a}, b}]@#, {x_} :>  x, All] &;
fb = Cases[MapAll[# /. {a : Except[_List], b__} :> {{a}, b} &, #], {x_} :> x, All] &;

Examples:

t1 = {{{1, 2, 3, 4}, {5, 6, {15, 16}, 7}}, {11, 12, 13, 14}}; 
t2 = {{a, 2, 3, 4}, {b, 6, {c, 8, {{d, 8, 9}, {e, 3, 3, 2}}, {f, 5, 7}}}};(*from cvgmt's answer*)
t3 = {{{1, 2, 3, 4}, {5, 6, {15, {16, {17, {18}}}}, 7}}, {11, 12, 13, 14}};

fa /@ {t1, t2, t3}
  {{1, 5, 15, 11}, 
   {a, b, c, d, e, f},
   {1, 5, 15, 16, 17, 18, 11}}
fb /@ {t1, t2, t3}
  {{1, 5, 15, 11}, 
   {a, b, c, d, e, f},
   {1, 5, 15, 16, 17, 18, 11}}

Correct answer by kglr on March 19, 2021

If integers are what counts as first elements:

Cases[t1, List[a_Integer, ___] :> a, All]
(* {1, 15, 5, 11} *)

Answered by Coolwater on March 19, 2021

Another way suitable for all list.

t2 = {{a, 2, 3, 4}, {b, 
    6, {c, 8, {{d, 8, 9}, {e, 3, 3, 2}}, {f, 5, 7}}}};
Cases [t2, {x_ /; ListQ[x] == False, ___}, {0, Infinity}]
First /@ %

The two outputs are

{{a, 2, 3, 4}, {d, 8, 9}, {e, 3, 3, 2}, {f, 5, 7}, {c, 
  8, {{d, 8, 9}, {e, 3, 3, 2}}, {f, 5, 7}}, {b, 
  6, {c, 8, {{d, 8, 9}, {e, 3, 3, 2}}, {f, 5, 7}}}}
{a, d, e, f, c, b}

Answered by cvgmt on March 19, 2021

Cases[First /@ Cases[t1, _List, Infinity], Except[_List]]
{1, 15, 5, 11}

Answered by Chris Degnen on March 19, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP