6
$\begingroup$

There is a list of lists:

{{0,0,0}, {0,0,1}, {0,1,0}, {0,1,1}, {1,0,0}, {1,0,1}, {1,1,0}, {1,1,1}}

I need to regrup it's elements according to a pattern: "if the first and the third elements are the same, make a partition". So I need to get following result:

{{{0,0,0},{0,1,0}}, {{0,0,1},{0,1,1}}, {{1,0,0},{1,1,0}}, {{1,0,1},{1,1,1}}}

How can I do it in Mathematica?

$\endgroup$
8
$\begingroup$
GatherBy[list, #[[{1, 3}]] &]

{{{0, 0, 0}, {0, 1, 0}},
{{0, 0, 1}, {0, 1, 1}},
{{1, 0, 0}, {1, 1, 0}},
{{1, 0, 1}, {1, 1, 1}}}

Alternatively,

Gather[list, #[[{1, 3}]] == #2[[{1, 3}]] &]

same result

or

Values @ GroupBy[list, #[[{1, 3}]] &]

same result

$\endgroup$
2
$\begingroup$

You can also select the ones with identical first and third entries, then use complement to get the rest:

list = {{0,0,0}, {0,0,1}, {0,1,0}, {0,1,1}, {1,0,0}, {1,0,1}, {1,1,0}, {1,1,1}};

{sel = Select[list, #[[1]] == #[[3]] &], Complement[list, sel]}
{{{0, 0, 0}, {0, 1, 0}, {1, 0, 1}, {1, 1, 1}}, 
 {{0, 0, 1}, {0, 1, 1}, {1, 0, 0}, {1, 1, 0}}}
$\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.