Python-如何仅将混合列表中的数字转换为浮点数? [英] Python - How to convert only numbers in a mixed list into float?

查看:268
本文介绍了Python-如何仅将混合列表中的数字转换为浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习Python,但遇到了问题,因此,如果我遇到类似问题:

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']

我该怎么做?

data_l = ['data', 18.8, 18.9, 0.0]

推荐答案

您可以创建一个简单的实用程序函数,该函数可以将给定值转换为浮点数,或者按原样返回该值:

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]

请不要使用内置函数的名称和类型,例如list等作为变量名.

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

由于您的数据实际上具有结构性,而不是真正的字符串和数字混合列表,因此看来(str, float, float, float)的4元组更合适:

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:]))

或在较旧的Python版本中

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:]]) 

这篇关于Python-如何仅将混合列表中的数字转换为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆