简体   繁体   English

Python-如何仅将混合列表中的数字转换为浮点数?

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

I'm trying to learn Python and i have a problem, so if i have something like that: 我正在尝试学习Python,但遇到了问题,因此,如果我遇到类似问题:

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

How do i make it like that? 我该怎么做?

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]

And please don't use names of builtin functions and types such as list etc. as variable names. 并且请不要将内置函数的名称和类型(例如list等)用作变量名。


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: 由于您的数据实际上具有结构,而不是真正的字符串和数字混合列表,因此看起来似乎由(str, float, float, float)的4元组更合适:

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

or in older Python versions 或旧版Python

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

You can use the str.isdigit method and a list comprehension: 您可以使用str.isdigit方法和列表理解:

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

Here you have a live example 这里有一个现场例子

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: isdigit将在正整数的情况下工作:

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

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]

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

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