Premiers éléments dans les sous-listes

Oct 03 2020

Donné

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

J'essaye d'obtenir des Firstéléments de sous-listes qui donneraient

{1,5,15,11}

Comment utiliser First, Takeou #1pour ce problème?

Réponses

7 kglr Oct 04 2020 at 05:57

Si la préservation de "l'ordre" des éléments extraits est importante, vous pouvez utiliser

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] &;

Exemples:

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}}
7 Coolwater Oct 03 2020 at 18:32

Si les entiers sont ce qui compte comme premiers éléments:

Cases[t1, List[a_Integer, ___] :> a, All]
(* {1, 15, 5, 11} *)
7 ChrisDegnen Oct 04 2020 at 01:22
Cases[First /@ Cases[t1, _List, Infinity], Except[_List]]
{1, 15, 5, 11}
6 cvgmt Oct 03 2020 at 23:18

Un autre moyen adapté à toutes les listes.

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 /@ %

Les deux sorties sont

{{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}