0

我正在尝试编写一个将整数转换为浮点数的函数,并将布尔值和字符串保持原样。

我已经定义了以下功能:

def if_int_to_float(value):

    if isinstance(value, bool):

        return value

    elif isinstance(value, int):

        return float(value)

    else:

        return value

当广泛使用时,我发现这个功能有点慢。有什么想法可以提高其性能/使其更 Pythonic 吗?

4

5 回答 5

3

在传递浮点数或字符串时,您可以删除一项检查并在一行上写入以稍微提高速度。bool 的情况已经非常快了。

Isinstance() 在这里给你带来了一些麻烦,因为 bools 也匹配 int 因此你的第一个 if 语句,所以你可以使用 type() 代替

def if_int_to_float(value):
    return value * 1.0 if type(value) == int else value
于 2019-05-08T16:07:00.957 回答
2

试试这个:

def if_int_to_float(value):

    if type(value) == int:

        return float(value)

    else:

        return value
于 2019-05-08T16:01:57.147 回答
1

您也许可以结合您的 if 条件。这将有所帮助,因为我们会根据输入短路 if 条件,这样可能会使您的代码更快!

def if_int_to_float(value):

    #If not boolean and int or float, convert to float
    if not isinstance(value, bool) and isinstance(value, int) or isinstance(value,float):
        return float(value)

    #Else return value
    else:
        return value

print(if_int_to_float('a'))
print(if_int_to_float(1))
print(if_int_to_float(1.0))
print(if_int_to_float(True))

输出将是

a
1.0
1.0
True
于 2019-05-08T15:54:48.197 回答
1

当数据在列表中时,使用lambda

data=[1,3,'j','oo']
sol = list(map(lambda x: float(x) if type(x)=='int' else x, data))
print(sol)

输出

[1.0, 3.0, 'j', 'oo']

或使用函数来测试单个值

def fun_int_to_float(value):
    if type(value)=='int':
        return float(value)
    return value
于 2019-05-08T15:56:15.830 回答
1

也许您可以尝试type()功能并获得结果。或者您可以使用异常处理来处理此类问题。但在这种情况下,正如评论中所指出的那样,如果是bool值,它会被转换True1.0和。False0.0

#using type() function
def if_int_to_float(value):
    if type(value) == int:
        return float(value)
    else:
        return value
于 2019-05-08T15:58:52.133 回答