5
$\begingroup$

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}}}
$\endgroup$
4
$\begingroup$

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

{}

| improve this answer | |
$\endgroup$
6
$\begingroup$

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

| improve this answer | |
$\endgroup$
4
$\begingroup$
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}},
{}}

| improve this answer | |
$\endgroup$

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.