I have a list:

testList={{"a","b 3","cd","ef 23"},{"z 12","y","x"}}

and wish to obtain

resultList={{"b 3","ef 23"},{"z 12"}}

...where I have deleted list items which do not include (string representations of) numbers. My thoughts on how to do this lead to the opposite of elegant code. Any ideas gratefully received.

Thank you for your responses!

I have a related question. Using the following list:

testList2={{"a","b 3","cd","ef 23"},{"z 12","y","x"},{"z","y"}}

I wish to keep list members that contain string representation of numbers and delete list members that don't, which will give:

resultList2={{"a","b 3","cd","ef 23"},{"z 12","y","x"}}
  • in this case, the third list item in testList2 gets dropped because its elements don't contain a string representation of a number.

Again, thanks for thoughts.

DeleteCases[testList, x_ /; StringFreeQ[x, DigitCharacter], {-1}]
{{"b 3", "ef 23"}, {"z 12"}}

Szabolcs offered a selection rather than deletion approach in a comment:

Select[StringContainsQ[DigitCharacter]] /@ testList

This works well for the list structure given, but if your structure is more irregular it may be somewhat harder to apply. Here's one approach:

testList /. x : {__String} :> Select[x, StringContainsQ[DigitCharacter]]
| improve this answer | |
  • 2
    $\begingroup$ Or Select[StringContainsQ[DigitCharacter]] /@ testList $\endgroup$ – Szabolcs Sep 16 '17 at 21:46
  • 2
    $\begingroup$ @Szabolcs I'm going to assume that since you put that in a comment and not an answer I am free to add it to mine, so I shall. $\endgroup$ – Mr.Wizard Sep 16 '17 at 21:55
  • $\begingroup$ Could also do Map[ReplaceAll[ x_ /; StringFreeQ[x, DigitCharacter] -> Nothing], testList, {2}]. $\endgroup$ – aardvark2012 Sep 17 '17 at 0:37

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.