4

I have a list of rules. Among them, I want to delete those rules which have first elements already shown up earlier. Following is a working example.

A = {1->2, 1->3, 2->5, 3->4, 4->1, 3->5};

Here, I want 1->3 to be deleted as 1 has already shown up in first elements 1->2. 2->5 should remain as 2 has not taken first position in earlier elements. So should 3->4 and 4->1. The last element 3->5 should be deleted as 3 is taken already by 3->4. Hence the output should be

{1->2, 2->5, 3->4, 4->1}
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
user49535
  • 1,225
  • 6
  • 9

2 Answers2

8

DeleteDuplicatesBy has better algorithmic complexity than DeleteDuplicates with a custom comparison function.

DeleteDuplicatesBy[A, First]
(* {1 -> 2, 2 -> 5, 3 -> 4, 4 -> 1} *)
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
5
DeleteDuplicates[{1 -> 2, 1 -> 3, 2 -> 5, 3 -> 4, 4 -> 1, 3 -> 5}, First[#1] == First[#2] &]
Hayashi Yoshiaki
  • 906
  • 4
  • 11