6
$\begingroup$

I have a list and need to remove certain members of the list.

lis = {f1,a,b,c,d,f2,e,g,h,i,f1,j,k,l,m,f2,n,o}

I need to remove each occurrence of f1 and the following two elements, and remove each occurrence of f2 and the following element. (f1 and f2 will always at least two elements apart). This gives:

res = {c,d,g,h,i,l,m,o}

ReplaceList would seem to be useful, but I am not able to see it. Thanks for any suggestions.

$\endgroup$

4 Answers 4

10
$\begingroup$

SequenceReplace

SequenceReplace[{f1, _, _} | {f2, _} -> Nothing] @ lis
{c, d, g, h, i, l, m, o}

Split+ ReplaceAll

ReplaceAll[{{f1, _, _, a___} | {f2, _, a___} :> a}] @
 Split[lis, #2 =!= f1 && #2 =!= f2 &]
{c, d, g, h, i, l, m, o}
$\endgroup$
2
  • $\begingroup$ This does not match res = {c,d,g,h,i,l,m,o}; but i could simply delete each occurrence of f1 and f2 to get res. Thanks @kglr! $\endgroup$
    – Suite401
    Commented Oct 17, 2020 at 23:40
  • $\begingroup$ @Suite401, fixed it. $\endgroup$
    – kglr
    Commented Oct 17, 2020 at 23:49
3
$\begingroup$
lis = {f1, a, b, c, d, f2, e, g, h, i, f1, j, k, l, m, f2, n, o};

An alternative is to use SequenceSplit and DeleteCases:

patt = {f1, _, _} | {f2, _};

Flatten[DeleteCases[SequenceSplit[lis, s : patt :> s], patt]]

(*{c, d, g, h, i, l, m, o}*)

Or using SequenceSplit and Cases:

Cases[s : Except[patt] :> Splice@s]@SequenceSplit[lis, s : patt :> s]

(*{c, d, g, h, i, l, m, o}*)
$\endgroup$
2
$\begingroup$
list = {f1, a, b, c, d, f2, e, g, h, i, f1, j, k, l, m, f2, n, o};

A variant of E. Chan-López answer

Flatten @ SequenceSplit[list, {f1, _, _} | {f2, _}]

{c, d, g, h, i, l, m, o}

$\endgroup$
1
$\begingroup$
lis = {f1, a, b, c, d, f2, e, g, h, i, f1, j, k, l, m, f2, n, o};
Catenate[
 Drop[#2, #1[[1]]] & @@@ 
  Partition[SplitBy[lis /. {f1 -> 2, f2 -> 1}, NumberQ], 2]]

yields: {c, d, g, h, i, l, m, o}

$\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.