5

Consider the following list, which is composed of sublists with different lengths

{{}, {{2, 2}, {7, 2}}, {{6, 3}}, {{5, 4}, {5, 5}}, {{4, 6}, {4, 7}, {4, 8}}, {}, {{6, 3}}}

How can this list be transformed into a list of the first elements, second elements, etc...i.e, the out come I would like to produce

{{{2, 2}, {6, 3}, {5, 4}, {4, 6}, {6, 3}}, {{7, 2}, {5, 5}, {4, 7}}, {{4, 8}}}
jarhead
  • 2,065
  • 12
  • 19

3 Answers3

6

You can use Flatten:

list = {
    {},
    {{2,2},{7,2}},
    {{6,3}},
    {{5,4},{5,5}},
    {{4,6},{4,7},{4,8}},
    {},
    {{6,3}}
};

Flatten[list, {2}]

{{{2, 2}, {6, 3}, {5, 4}, {4, 6}, {6, 3}}, {{7, 2}, {5, 5}, {4, 7}}, {{4, 8}}}

Carl Woll
  • 130,679
  • 6
  • 243
  • 355
4

Maybe this way?

data = {{}, {{2, 2}, {7, 2}}, {{6, 3}}, {{5, 4}, {5, 5}}, {{4, 6}, {4, 7}, {4, 8}}, {}, {{6, 3}}};
get[a_, k_] := Map[If[Length[#] >= k, #[[k]], Nothing] &, a];
get[data, 1]
get[data, 2]
get[data, 3]
get[data, 4]

{{2, 2}, {6, 3}, {5, 4}, {4, 6}, {6, 3}}

{{7, 2}, {5, 5}, {4, 7}}

{{4, 8}}

{}

Henrik Schumacher
  • 106,770
  • 7
  • 179
  • 309
4
lst = {{}, {{2, 2}, {7, 2}}, {{6, 3}}, {{5, 4}, {5, 5}},
   {{4, 6}, {4, 7}, {4, 8}}, {}, {{6, 3}}};

Extract[lst, #] & /@ GatherBy[Position[lst, _, {2}, Heads -> False], Last]

{{{2, 2}, {6, 3}, {5, 4}, {4, 6}, {6, 3}},
{{7, 2}, {5, 5}, {4, 7}},
{{4, 8}}}

or

parts[l_][k_] := Join @@ MapIndexed[If[Last[#2] == k, #, ## &[]] &, l, {2}]
parts[lst] /@ Range[4]]

{{{2, 2}, {6, 3}, {5, 4}, {4, 6}, {6, 3}},
{{7, 2}, {5, 5}, {4, 7}},
{{4, 8}},
{}}

kglr
  • 394,356
  • 18
  • 477
  • 896