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

后端 未结 4 1615
不思量自难忘°
不思量自难忘° 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-06 23:59

    Universal approach:

    def validate_number(s):
        try:
            return float(s)
        except (ValueError, TypeError):
            return s
    
    data = [validate_number(s) for s in data]
    

    In case the structure is fixed:

    data = [s if i == 0 else float(s) for i, s in enumerate(data)]
    

    Another one:

    data = [data[0]] + [float(s) for s in data[1:]]
    

    isdigit would work in case of positive integers:

    data = [int(s) if s.isdigit() else s for s in data]
    

提交回复
热议问题