我有一些Python代码,它运行一个字符串列表,并将它们转换为整数或浮点数(如果可能的话)。对整数执行此操作非常简单

if element.isdigit():
  newelement = int(element)

浮点数比较难。现在我正在使用partition('.')来分割字符串,并检查以确保一侧或两侧都是数字。

partition = element.partition('.')
if (partition[0].isdigit() and partition[1] == '.' and partition[2].isdigit()) 
    or (partition[0] == '' and partition[1] == '.' and partition[2].isdigit()) 
    or (partition[0].isdigit() and partition[1] == '.' and partition[2] == ''):
  newelement = float(element)

这是可行的,但显然if语句有点麻烦。我考虑的另一个解决方案是将转换封装在一个try/catch块中,看看它是否成功,如这个问题所述。

有人有其他想法吗?对分区和尝试/捕获方法的相对优点有什么看法?


当前回答

这就像一个魅力:

[dict([a,int(x) if isinstance(x, str)
 and x.isnumeric() else float(x) if isinstance(x, str)
 and x.replace('.', '', 1).isdigit() else x] for a, x in json_data.items())][0]

其他回答

我写了自己的函数。而不是float(value),我使用floatN()或floatZ()。如果该值不能被转换为浮点类型,则返回None或0.0。我将它们保存在一个称为safeCasts的模块中。

def floatN(value):
    try:
        if value is not None:
            fvalue = float(value)
        else:
            fvalue = None
    except ValueError:
        fvalue = None

    return fvalue


def floatZ(value):
    try:
        if value is not None:
            fvalue = float(value)
        else:
            fvalue = 0.0
    except ValueError:
        fvalue = 0.0

    return fvalue

在其他模块中,我导入它们

from safeCasts import floatN, floatZ

然后使用floatN(value)或floatZ(value)来代替float()。显然,您可以将此技术用于所需的任何强制转换函数。

一个简单的函数,不需要try和except操作就可以得到数字的类型

def number_type(number):
    if number.isdigit():
        return int(number)
    elif number.replace(".","").isdigit():
        return float(number)
    else:
        return(type(number))

我正在寻找一些类似的代码,但看起来使用try/excepts是最好的方法。 这是我正在使用的代码。它包括一个在输入无效时的重试函数。我需要检查输入是否大于0,如果是,则将其转换为浮点数。

def cleanInput(question,retry=False): 
    inputValue = input("\n\nOnly positive numbers can be entered, please re-enter the value.\n\n{}".format(question)) if retry else input(question)
    try:
        if float(inputValue) <= 0 : raise ValueError()
        else : return(float(inputValue))
    except ValueError : return(cleanInput(question,retry=True))


willbefloat = cleanInput("Give me the number: ")

如果你不需要担心科学或其他数字的表达式,并且只处理可以是带句号或不带句号的数字的字符串:

函数

def is_float(s):
    result = False
    if s.count(".") == 1:
        if s.replace(".", "").isdigit():
            result = True
    return result

Lambda版本

is_float = lambda x: x.replace('.','',1).isdigit() and "." in x

例子

if is_float(some_string):
    some_string = float(some_string)
elif some_string.isdigit():
    some_string = int(some_string)
else:
    print "Does not convert to int or float."

这样你就不会意外地将一个int型转换为浮点型。

尝试转换为float。如果有错误,打印ValueError异常。

try:
    x = float('1.23')
    print('val=',x)
    y = float('abc')
    print('val=',y)
except ValueError as err:
    print('floatErr;',err)

输出:

val= 1.23
floatErr: could not convert string to float: 'abc'