如果可能,如何在 python 的字典中将字符串转换为整数或浮点数?

How to convert a string to integer or float if possible in dictionary in python?

我有以下词典:

param = {'lgb__boosting_type': 'dart',
 'lgb__colsample_bytree': '0.7135948579099038',
 'lgb__feature_fraction': '0.98283890190338',
 'lgb__learning_rate': '0.041712347301680976',
 'lgb__max_depth': '3',
 'lgb__metric': 'rmse',
 'lgb__min_data_in_leaf': '90',
 'lgb__num_leaves': '55',
 'lgb__objective': 'binary',
 'lgb__reg_lambda': '0.013449050509130145',
 'lgb__subsample': '0.8473591109865588'}

现在我想将字典的键值转换为整数或浮点数(整数优先于浮点数类型),否则应将其保留为字符串。

到目前为止我的程序:

    def int_or_fl(value):
        try:
            value = float(value)
        except ValueError:
            value = int(value)
            except ValueError:
                None

 param = {key:int_or_fl(items) for key,items in param.items()}

但我认为您不能在另一个 except 命令中引发 except 命令。

在第一个 except 后添加另一个 try 块。

def int_or_fl(value):
    try:
        value = float(value)
    except ValueError:
        try:
            value = int(value)
        except ValueError:
            pass
    return value

如果你想避免嵌套try-except,你可以这样做:

def int_or_fl(value):
    try:
        return float(value)
    except ValueError:
        pass
    try:
        return int(value)
    except ValueError:
        pass
    return value

这应该有效:

import re
re_int = re.compile(r'\d+$')
re_float = re.compile(r'\d+\.\d+$')

def is_int(val):
    return bool(re_int.match(val))
def is_float(val):
    return bool(re_float.match(val))

def int_or_float(val):
    if is_int(val):
        return int(val)
    if is_float(val):
        return float(val)
    return val