简体   繁体   English

如何从列表中删除包含字母的字符串?

[英]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.我只想将数字保留在列表中并将它们转换为float值。 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.当我从 Arduino 执行 serial.readline() 时,会创建该列表,它为我提供了一个由命令和数据点组成的字符串。 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.我做了一个 list.split(delimiter=',') 并且只想拥有用于未来计算的数据点。

Probably the best way to see whether a string can be cast to float is to just try to cast it.查看是否可以将字符串强制转换为float的最佳方法可能是try进行强制转换。

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

Afterwards, res is [-224.3, 45.1]之后, res[-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.你也可以将这个列表理解,像[float(x) for x in lst if is_float(x)] ,但对于这一点,你需要一个功能is_float ,将基本上做同样的事情:尝试将它转换为浮动并返回 True,否则返回 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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