简体   繁体   English

如何使其成为列表理解?

[英]How to make this into a list comprehension?

I have a list of strings.我有一个字符串列表。 Some of these strings can be converted to floats, other not.其中一些字符串可以转换为浮点数,其他的则不能。 I'm trying to extract those that can be converted to floats.我正在尝试提取那些可以转换为浮点数的。 For now, I am using the following code现在,我正在使用以下代码

my_strings = ['1', '42', '.3', 'a', 'b', 'c']
my_floats = []
for e in my_strings:
    try:
        my_floats.append(float(e))
    except ValueError:
        pass

Is there a way of doing this operation as a list comprehension?有没有办法将此操作作为列表理解?

You could write a safeFloat function that converts a string to a float and uses a default value for invalid strings.您可以编写一个 safeFloat function 将字符串转换为浮点数并对无效字符串使用默认值。 This could be used in a list comprehension or mapped with a filter if you don't want items that aren't numeric:如果您不想要非数字的项目,这可以用于列表理解或使用过滤器映射:

def safeFloat(S,default=None):
    try:    return float(S)
    except: return default


my_strings = ['1', '42', '.3', 'a', 'b', 'c']

my_floats  = [safeFloat(s,0) for s in my_strings]

[1.0, 42.0, 0.3, 0, 0, 0]

my_floats = [float(s) for s in my_strings if safeFloat(s) != None]

[1.0, 42.0, 0.3]

my_floats  = list(filter(None,map(safeFloat,my_strings)))

[1.0, 42.0, 0.3]

If you're doing this often on lists or iterators, you can further encapsulate the conversion in a function that converts and filters multiple items如果您经常在列表或迭代器上执行此操作,则可以进一步将转换封装在 function 中,该 function 可以转换和过滤多个项目

def getFloats(S,default=None):
    yield from filter(None,map(safeFloat,S))

my_floats = [*getFloats(my_strings)]

[1.0, 42.0, 0.3]

You should not rely on exceptions for your code logic.您不应该依赖代码逻辑的异常。 Try this:尝试这个:

my_strings = ['1', '42', '.3', 'a', 'b', 'c']
my_floats = [float(string) for string in my_strings if string.replace('.','',1).isdigit()]

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

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