4
$\begingroup$

How to use DeleteDuplicates or DeleteDuplicatesBy to delete duplicates inside list if I want to treat non-identical numbers, say $1$ and $2$ as identical?

I would define list of rules for identical numbers this way:

identicalrules={{1,2},{3,4},{5,7},{6,8}} 

Meaning that I want to treat $1$ and $2$ as identical, $3$ and $4$ as identical, $5$ and $7$ as identical and $6$ and $8$ as identical.

Then I want to delete duplicates of this list:

li={{1,2,3},{3,5,8},{4,7,6},{2,1,3}} 

Output should be:

{{1,2,3},{3,5,8}} 

because according to my rules {2,1,3} is duplicate of {1,2,3} and {4,7,6} is duplicate of {3,5,8}.

I would like the code to be something like this:

DeleteDuplicates[li,identicalrules] 

or

DeleteDuplicatesBy[li,identicalrules] 

I also tried a simple example where $1$ and $2$ should be treated as identical:

DeleteDuplicatesBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, # == 1 \[Or] # == 2 &] 

But the output was:

{1, 3} 

Instead of:

{1,3,4,5,6,7,8,9} 

which I wanted to be like it.

Attention: While I want to treat $1$ and $2$ as identical it does not mean I accept replacing $1$ by $2$ or vice-versa.

$\endgroup$

1 Answer 1

3
$\begingroup$
irules = Join[Rule @@@ identicalrules]; DeleteDuplicatesBy[li, # /. irules &] 

{{1, 2, 3}, {3, 5, 8}}

DeleteDuplicatesBy[{1, 2, 3, 4, 5, 6, 7, 8, 9}, # /. 2 -> 1 &] 

{1, 3, 4, 5, 6, 7, 8, 9}

Alternatively

ClearAll[foo] foo[x_] := x Table[foo[i[[2]]] = i[[1]], {i, identicalrules}]; DeleteDuplicatesBy[li, foo /@ # &] {{1, 2, 3}, {3, 5, 8}} 
$\endgroup$
2
  • $\begingroup$ It could be without "Reverse /@" if I am not mistaken. $\endgroup$ Commented Jan 25, 2020 at 0:14
  • $\begingroup$ @azerbajdzan, you are right. $\endgroup$ Commented Jan 25, 2020 at 0:15

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.