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

后端 未结 4 1609
不思量自难忘°
不思量自难忘° 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

    The above-mentioned approaches are working but since a mixed list can also contain an integer value I added an extra checking.

    def validate(num):
        try:
            return int(num)
        except (ValueError, TypeError):
            try:
                return float(num)
            except (ValueError, TypeError):
                return num
    
    
    vals_ = ['cat' ,'s-3-f','7390.19','12']
    new_list = [validate(v) for v in vals_]  
    

    Output:

    ['cat', 's-3-f', 7390.1, 12]
    

提交回复
热议问题