0
$\begingroup$

I have a nested list where all sublists have a length 2, eg:

{{1,2}, {1,1}, {3,4}, {3,5}, ...}  

I need to filter it for two requirements:

  • Delete all sub-lists with the same First (except the first such sub-list)
  • Delete all sub-lists with First equal to Last

I get a huge construction:

DeleteDuplicates[
            DeleteCases[list, e_ /; First@e == Last@e],
        First@#1 == First@#2 &
        ]

Could it be golfed, for example, including union of duplicates in DeleteCases?

$\endgroup$
5
  • 1
    $\begingroup$ You put code optimization in your title – What does this mean? What is wrong with your current code? It's really not a huge construction. What you can do is to use DeleteDuplicatesBy[..., First] instead of DeleteDuplicates[..., First@#1 == First@#2 &]. $\endgroup$
    – Domen
    Commented Apr 30 at 12:24
  • $\begingroup$ @Domen, yes, it's much better with DeleteDuplicatesBy! But may be is it possible to do all filtering with one function? $\endgroup$
    – lesobrod
    Commented Apr 30 at 12:27
  • $\begingroup$ DeleteDuplicatesBy[DeleteCases[{a_, a_}]@list, First] $\endgroup$
    – eldo
    Commented Apr 30 at 12:32
  • $\begingroup$ You mean like DeleteDuplicates[list, First@#1 == First@#2 || First@#1 == Last@#1 || First@#2 == Last@#2 &]? $\endgroup$
    – Domen
    Commented Apr 30 at 12:38
  • 1
    $\begingroup$ Does it absolutely have to be one function? If not I feel like something like: $$ $$ del = DeleteDuplicatesBy[list, First]; $$ $$ Select[del, ! Equal @@ # &] $$ $$ is short and readable, and also gives good performance for large lists. $\endgroup$
    – ydd
    Commented Apr 30 at 13:27

1 Answer 1

2
$\begingroup$

Not sure what you consider optimal, but in response to your comment

is it possible to do all filtering with one function?

you can certainly compose the two operations into one function and even use a point-free style:

DeleteDuplicatesBy[First]@*Select[Apply[Unequal]]@list
$\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.