7
$\begingroup$

With a nested list such as

listA = {{{a,b,c},{1,0,0}}, {{a,b,c},{0,1,0}}, {{d,e,f},{1,1,0}}};

How can I create

listB = {{{a,b,c},{{1,0,0},{0,1,0}}}, {{d,e,f},{1,1,0}}};

and so-forth for any length of listA?

$\endgroup$
7
$\begingroup$
KeyValueMap[List] @ GroupBy[listA, First -> Last] 
Values @ GroupBy[listA, First, {#[[1, 1]], #[[All, 2]]}&] 
KeyValueMap[List] @ Merge[Association /@ Rule @@@ listA, Identity]
{#[[1, 1]], #[[All, 2]]} & /@ GatherBy[listA, First]

all give

{{{a, b, c}, {{1, 0, 0}, {0, 1, 0}}}, {{d, e, f}, {{1, 1, 0}}}}

$\endgroup$
  • $\begingroup$ Very nice and concise. And general! $\endgroup$ – Phillip Dukes Feb 24 '18 at 22:49
  • $\begingroup$ @PhillipDukes, thank you for the accept. $\endgroup$ – kglr Feb 24 '18 at 22:59

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.