I have a list:

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"}}

Looking only at list members that have identical values at the first, second, fourth and sixth positions, I would like to delete those list members whose third and fifth positions are "xx", which gives:

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

A previous suggestion was:

DeleteDuplicatesBy[MapAt["xx" &, {{3}, {5}}]]@lis

which gives:

badRes = {{"a","b","c","d","e","f"}, {"i","j","k","l","m","f"}}

which omits one desired element.

  • $\begingroup$ What should the response be to 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"}, {"i", "j", "xx", "l", "xx", "f"} , {"a", "b", "xx", "d", "p", "f"} } ? $\endgroup$
    – Syed
    Commented Sep 25, 2023 at 3:42
  • $\begingroup$ Try: lis /. {_, _, x_, _, x_, _} -> Nothing $\endgroup$ Commented Sep 25, 2023 at 6:47
  • $\begingroup$ @syed just saw your comment, fortunately, if there is "xx" at position three, there will always be an "xx" at position five in this data set. $\endgroup$
    – Suite401
    Commented Sep 25, 2023 at 15:12
  • $\begingroup$ @Daniel Huber thanks! $\endgroup$
    – Suite401
    Commented Sep 25, 2023 at 15:13

2 Answers 2

rep[a_] /; a[[3]] == "xx" && a[[5]] == "xx" := Nothing
rep[a_] := a

rep /@ lis

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

Slower Alternatives:

SequenceReplace[lis, {{_, _, "xx", _, "xx", _} ..} :> Nothing]

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

and, giving the same result,

SubsetReplace[lis, {{_, _, "xx", _, "xx", _} ..} :> Nothing]

Another way using Select:

Select[lis, Not[#[[3]] == "xx" && #[[5]] == "xx"] &] === res


Also, using DeleteCases:

DeleteCases[lis, {__, "xx", _, "xx", __}] === res


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.