Skip to content Skip to sidebar Skip to footer

Most Efficient Way To Remove Non-numeric List Entries

I'm looking to 'clean' a list by excluding any items which contain characters other than 0-9, and wondering if there's a more efficient way than e.g. import re invalid = re.compile

Solution 1:

Anything wrong with the string method isdigit ?

>>>ls = ['1a', 'b3', '1']>>>cleaned = [ x for x in ls if x.isdigit() ]>>>cleaned
['1']
>>>

Solution 2:

You can use isnumeric function. It checks whether the string consists of only numeric characters. This method is present only on unicode objects. It won't work with integer or float values

myList = ['text', 'another text', '1', '2.980', '3']
output = [ a for a in myList if a.isnumeric() ]
print( output )      
# Output is : ['1', '3']

Ref: https://www.tutorialspoint.com/python/string_isnumeric.htm

Post a Comment for "Most Efficient Way To Remove Non-numeric List Entries"