1

Original Question: I have a list {{a, 1}, {b, 3}, {c, 1}, {d, 2}, {e, 3}}. I want to be able to group the the first number in each pair that has the same second number in the pair. So i would get a list like

{{a,c},d,{b,e}} so

{a,c} is from {a,1} and {c,1}

d is from {d,2}

{b,e} is from {b,3} and {e,3}

ADDonut
  • 139
  • 6

2 Answers2

2

I am not sure I understand. Here are some ways to group by last element:

list={{1, 1}, {1, 3}, {2, 1}, {2, 2}, {2, 3}}
GatherBy[list, Last]
GroupBy[list, Last]
Last@Reap[Sow[{##}, #2] & @@@ list, _, Rule]

yielding respectively:

{{{1, 1}, {2, 1}}, {{1, 3}, {2, 3}}, {{2, 2}}}

<|1 -> {{1, 1}, {2, 1}}, 3 -> {{1, 3}, {2, 3}}, 2 -> {{2, 2}}|>

{1 -> {{1, 1}, {2, 1}}, 3 -> {{1, 3}, {2, 3}}, 2 -> {{2, 2}}}

GroupBy has other useful features.

ubpdqn
  • 60,617
  • 3
  • 59
  • 148
  • 1
    Probably GroupBy[list, Last -> First] with skiping {} from one element lists. Not so sure about an order and its meaning. – Kuba Jun 17 '16 at 07:21
  • I don't mind the extra {}. But how do i use this as a list it has the weird form <|1 -> {1, 2}, 3 -> {1, 2}, 2 -> {2}|> – ADDonut Jun 17 '16 at 07:28
  • @MTR that is an Association (see documentation), You can "normalize" it with Normal@GroupBy[list,Last]. – ubpdqn Jun 17 '16 at 07:31
  • @MTR or Values @ GroupBy[list, Last -> First] – Kuba Jun 17 '16 at 07:34
2

I think I know what you need:

SortBy[GatherBy[list,Last],Last@*Last][[;;,;;,1]]/.{x_?AtomQ}->x

The result is:

{{a,c},d,{b,e}}

This will gather the elements by the last member of each small list, sort it by the index number and then throw away all the index numbers. Finally, it can change all one element list into the number itself.

Will this help directly?

Wjx
  • 9,558
  • 1
  • 34
  • 70
  • @HighPerformanceMark oh yes! I mistype it cause I'm currently typing with my tiny phone on my hand. Thanks for informing! – Wjx Jun 17 '16 at 07:32