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$
1

1 Answer 1

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$
2
  • $\begingroup$ Very nice and concise. And general! $\endgroup$ Feb 24, 2018 at 22:49
  • $\begingroup$ @PhillipDukes, thank you for the accept. $\endgroup$
    – kglr
    Feb 24, 2018 at 22:59

Your Answer

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

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