4
$\begingroup$

I'm trying to remove nested lists that are associated with a key

a = {{1, 2, 3, 4} -> 1, {5, 6, 7, 8} -> 1, {9, 10, 11, 12} -> 2, {13, 14, 15, 16} -> 2};

In order to create two separate lists where;

b contains the nested lists associated with the key 1, but without the key;

c contains the nested lists associated with the key 2, but without the key.

Would anybody be able to help?

Thanks!

$\endgroup$

2 Answers 2

7
$\begingroup$

You can use GroupBy:

{b, c} = GroupBy[a, Last, Keys] /@ {1, 2}

{{{1, 2, 3, 4}, {5, 6, 7, 8}},
{{9, 10, 11, 12}, {13, 14, 15, 16}}}

Alternatively, you can use Merge after reversing each element of a:

{b2, c2} = Values @ Merge[Identity] @ (Reverse /@ a) ;
{b2, c2} == {b, c}

True

You can also get the same result using Cases:

{b3, c3} = Cases[a, Rule[p_, #] :> p] & /@ {1, 2} 
{b3, c3} == {b, c}

True

$\endgroup$
2
  • $\begingroup$ Thank you for your reply. Would this work this same for a list that had 0 for its key? Eg: a={{1,2,3,4}->0, {5,6,7,8}->1} $\endgroup$
    – isaac5122
    Feb 13, 2020 at 21:05
  • $\begingroup$ @Luke4737, if you mean something like ax = {{1, 2, 3, 4} -> 1, {5, 6, 7, 8} -> 1, {9, 10, 11, 12} -> 2, {13, 14, 15, 16} -> 2, {stuff, etc} -> 0} as input list, you can use {l0, l1, l2} = GroupBy[ax, Last, Keys] /@ {0, 1, 2} (or more generally, separatedlists = GroupBy[ax, Last, Keys] /@ ax[[All, -1]]) Similarly, for other methods. $\endgroup$
    – kglr
    Feb 13, 2020 at 21:18
5
$\begingroup$

With Query.

Query[GroupBy[Values -> Keys] /* KeySort /* Values]@a

or without

Values@KeySort@GroupBy[Values -> Keys]@a

Both give

{{{1, 2, 3, 4}, {5, 6, 7, 8}}, 
 {{9, 10, 11, 12}, {13, 14, 15, 16}}}

KeySort ensures the key sets are order by their value.

Hope this helps.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.