A few days ago I posed a question at [deletion of list members by rules][1]. @eldo and @E. Chan-López provided useful answers.

Unfortunately I found a case where the methods suggested did not provide the desired result, my error for not thinking of all possible cases in my data set.

The original problem was to remove one of a pair of near-duplicate list members marked by an "xx" in the 3rd and 5th position, the 1st, 2nd, 4th, and 6th positions being the same in each pair of elements.

The additional case is when there is only one list element with "xx" at the 3rd and 5th position, so no pair is present. The suggested methods delete such unpaired elements containing the "xx"s but I wish to keep them when they aren't part of a pair

Easier to explain with an example:

lis = {{"a","b","c","d","e","f"}, {"a","b","g","d","p","f"}, 
      {"i","j","k","l","m","f"}, {"a","b","xx","d","xx","f"},

to give:

res = {{"a","b","c","d","e","f"}, {"a","b","g","d","p","f"}, 
      {"i","j","k","l","m","f"}, {"q","r","xx","s","xx","t"}}

The previous solutions gave:

res = {{"a","b","c","d","e","f"}, {"a","b","g","d","p","f"}, 

Thanks again for any ideas... [1]: Deletion of list members by rules


1 Answer 1

lis = {{"a", "b", "c", "d", "e", "f"}, {"a", "b", "g", "d", "p", 
   "f"}, {"i", "j", "k", "l", "m", "f"}, {"a", "b", "xx", "d", "xx", 
   "f"}, {"q", "r", "xx", "s", "xx", "t"}}

GatherBy[lis, {#[[1]], #[[2]], #[[4]], #[[6]]} &] /. {a__List, {_, _, 
     "xx", _, "xx", _}} :> {a} // Map[Apply[Sequence]]

{{"a", "b", "c", "d", "e", "f"}, {"a", "b", "g", "d", "p", "f"}, {"i", "j", "k", "l", "m", "f"}, {"q", "r", "xx", "s", "xx", "t"}}

  • 1
    $\begingroup$ Thanks @Syed again! $\endgroup$
    – Suite401
    Commented Sep 30, 2023 at 3:34

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.