3
$\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$
7
$\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}
| improve this answer | |
$\endgroup$
  • $\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 Oct 17 at 23:40
  • $\begingroup$ @Suite401, fixed it. $\endgroup$ – kglr Oct 17 at 23:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.