8
$\begingroup$

I have a list of strings:

lis = {"a","1","b","2","c","3","a","d","4"}

and would like to get:

res = {"a","b","2","c","3","a","d","4"}

where each occurrence of "a" that is immediately followed by (a string representation of) an integer, that integer is deleted from the list. ToExpression followed by IntegerQ seems inefficient, would be grateful for thoughts.

$\endgroup$
8
$\begingroup$

SequenceReplace:

SequenceReplace[lis, {"a", _?(StringMatchQ[NumberString])} :> "a"]

 {"a", "b", "2", "c", "3", "a", "d", "4"}

Also

SequenceReplace[lis, {"a", _?(IntegerQ @* ToExpression)} :> "a"]

 {"a", "b", "2", "c", "3", "a", "d", "4"}

Split + ReplaceAll

Flatten[Split[lis, # == "a" &] /. {"a", _?(IntegerQ@*ToExpression) } :> "a"]

 {"a", "b", "2", "c", "3", "a", "d", "4"}

|improve this answer|||||
$\endgroup$
  • 1
    $\begingroup$ Thank you both! $\endgroup$ – Suite401 Sep 11 '18 at 4:19
6
$\begingroup$

The following works for your example. But I am not sure that it will work for you if your example is not descriptive enough for some more general situation you have in mind.

lis = {"a", "1", "b", "2", "c", "3", "a", "d", "4"};
Flatten[Partition[lis, UpTo[2]] /. {"a", "1"} -> "a"]
{"a", "b", "2", "c", "3", "a", "d", "4"}
|improve this answer|||||
$\endgroup$

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.