6
$\begingroup$

I've been working with lists and am stuck on creating lists within a list based on the first element within that list. So for instance, if I have the list:

> list={{John,42},{Mary,52},{John,30},{Mary,25},{Joe,10}}

I would like to return this:

{{{Joe,10}},{{John,42},{John,30}},{{Mary,52},{Mary,25}}}

As you can see, this is basically a reorganized list within a list based on SortBy[...,First]

I can create the sorted version by simply doing:

SortBy[list,First]

Which would return:

{{Joe,10},{John,42},{John,30},{Mary,52},{Mary,25}}

But I would also like for each list to be grouped into another list based on the name

Any help would be much appreciated.

$\endgroup$

2 Answers 2

6
$\begingroup$
GatherBy[SortBy[list, First], First]
GatherBy[Sort@list, First]
SplitBy[Sort@list, First]
Values @ GroupBy[First] @ Sort@list

{{{Joe, 10}}, {{John, 30}, {John, 42}}, {{Mary, 25}, {Mary, 52}}}

SortBy[GatherBy[list, First], First]
GatherBy[SortBy[list, {First}], First]
Sort[GatherBy[list, First]] (* thanks: J.M *)
Values @ Sort @ GroupBy[First] @ list

{{{Joe, 10}}, {{John, 42}, {John, 30}}, {{Mary, 52}, {Mary, 25}}}

$\endgroup$
2
  • 1
    $\begingroup$ Sort[GatherBy[{{"John", 42}, {"Mary", 52}, {"John", 30}, {"Mary", 25}, {"Joe", 10}}, First]] works, too. $\endgroup$ Commented Oct 13, 2017 at 16:52
  • $\begingroup$ @J.M, yes of course. Thank you. $\endgroup$
    – kglr
    Commented Oct 13, 2017 at 16:55
4
$\begingroup$

Do you mean something like obtained from

KeySort[Map[SortBy[#, Last] &, GroupBy[list, First]]]

(* <|Joe -> {{Joe, 10}}, John -> {{John, 30}, {John, 42}}, Mary -> {{Mary, 25}, {Mary, 52}}|> *)

or by

Values[KeySort[Map[SortBy[#, Last] &, GroupBy[list, First]]]]

(* {{{Joe, 10}}, {{John, 30}, {John, 42}}, {{Mary, 25}, {Mary, 52}}} *)

?

$\endgroup$

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.