I have a list of tuples like this:

{{1,a,b},{1,1,b},{1,a,a},{b,a,1},{b,a,b}}

I would like to find a way to delete all those tuples in the list that contain a duplicate unless that duplicate is a 1. Therefore, the desired result given the example input above would be:

{{1,a,b},{1,1,b},{b,a,1}}

I will also need to delete duplicate elements within the list (irrespective of sorting) but that is easily done (i.e. only keep one of {1,a,b} and {b,a,1}).

I would like it to work for generic length tuples too, for example:

{{1,1,1,1},{1,a,a,b},{a,b,b,c},{1,a,b,c},{1,1,a,b}}

would become

{{1,1,1,1},{1,a,b,c},{1,1,a,b}}
  • Before I clicked into the post I thought it was a meta question (from the title) :P – TheSimpliFire Oct 17 at 19:21
up vote 12 down vote accepted
list = {{1, a, b}, {1, 1, b}, {1, a, a}, {b, a, 1}, {b, a, b}};
l1 = Select[list,DuplicateFreeQ[DeleteCases[#,1]]&]

{{1, a, b}, {1, 1, b}, {b, a, 1}}

DeleteDuplicatesBy[Sort]@l1

{{1, a, b}, {1, 1, b}}

list2 = {{1, 1, 1, 1}, {1, a, a, b}, {a, b, b, c}, {1, a, b, c}, {1,  1, a, b}};
l2 = Select[list2, DuplicateFreeQ[DeleteCases[#, 1]] &] 

{{1, 1, 1, 1}, {1, a, b, c}, {1, 1, a, b}}

DeleteDuplicatesBy[Sort]@l2

{{1, 1, 1, 1}, {1, a, b, c}, {1, 1, a, b}}

This defines a function which deletes duplicates while ignoring the duplicates of given parameters:

ClearAll[deleteDuplicates];
deleteDuplicates[a__] := Pick[#, 
    SameQ[#, DeleteDuplicates[#, 
       Apply[And, Join[{SameQ[#1, #2]}, 
         Function[temp, UnsameQ[temp, #1]] /@ {a}]
       ]& ]
    ] & /@ #] &;

For example:

deleteDuplicates[1][{{1, 1}, {1, 2}, {2, 2}, {2, 3}, {3, 3}}]

deleteDuplicates[2][{{1, 1}, {1, 2}, {2, 2}, {2, 3}, {3, 3}}]

deleteDuplicates[1, 2][{{1, 1}, {1, 2}, {2, 2}, {2, 3}, {3, 3}}]

gives

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

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

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

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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