简体   繁体   中英

How to remove strings that contain letters from a list?

I have a list containing strings with both letters, characters and and numbers:

list = ['hello', '2U:', '-224.3', '45.1', 'SA 2']

I want to only keep the numbers in a list and convert them to float values. How can I do that? I want the list to look like this:

list = ['-224.3'. '45.1']

The list is created, when I do a serial.readline() from a Arduino, which gives me a string comprised of commands and data points. So i looked like this:

'hello,2U:,-224.3,45.1,SA 2'

I did a list.split(delimiter=',') and wanted to only have the data points for future calculations.

Probably the best way to see whether a string can be cast to float is to just try to cast it.

res = []
for x in lst:
    try:
        res.append(float(x))
    except ValueError:
        pass

Afterwards, res is [-224.3, 45.1]

You could also make this a list comprehension, something like [float(x) for x in lst if is_float(x)] , but for this you will need a function is_float that will essentially do the same thing: Try to cast it as float and return True, otherwise return False. If you need this just once, the loop is shorter.

You can try something like below -

def isNum(s):
    try:
            float(s)
            return True
    except ValueError:
            return False
lst = ['hello', '2U:', '-224.3', '45.1', 'SA 2']
bools = list(map(lst,isNum))
deleted = 0
for idx, val in enumerate(bools):
    if val:
            continue
    else:
            del lst[idx-deleted]
            deleted = deleted + 1

EDIT:

Or you can use

def isNum(s):
    try:
            float(s)
            return True
    except ValueError:
            return False
lst = ['hello', '2U:', '-224.3', '45.1', 'SA 2']
lst = list(filter(isNum, lst))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM