Python - How to convert only numbers in a mixed list into float?

后端 未结 4 1612
不思量自难忘°
不思量自难忘° 2020-12-06 23:47

I\'m trying to learn Python and i have a problem, so if i have something like that:

data_l = [\'data\', \'18.8\', \'17.9\', \'0.0\']

How d

4条回答
  •  没有蜡笔的小新
    2020-12-07 00:04

    You could create a simple utility function that either converts the given value to a float if possible, or returns it as is:

    def maybe_float(s):
        try:
            return float(s)
        except (ValueError, TypeError):
            return s
    
    orig_list = ['data', '18', '17', '0']
    the_list = [maybe_float(v) for v in orig_list]
    

    And please don't use names of builtin functions and types such as list etc. as variable names.


    Since your data actually has structure instead of being a truly mixed list of strings and numbers, it seems a 4-tuple of (str, float, float, float) is more apt:

    data_conv = (data_l[0], *(float(v) for v in data_l[1:]))
    

    or in older Python versions

    # You could also just convert each float separately since there are so few
    data_conv = tuple([data_l[0]] + [float(v) for v in data_l[1:]]) 
    

提交回复
热议问题