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$

2 Answers 2

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

$\endgroup$
0
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"}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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