在 Julia 中将 float 或字符串类型的数组转换为 int 类型(从 Python 复制 int())

Moh*_*aad 4 string integer type-conversion julia

我想复制 python 函数的功能int(),它可以将string或转换floatint以 10 为基数的类型。

参考: https: //www.w3schools.com/python/ref_func_int.asp

我开发了一个小代码来执行此执行:

a = "5.9"
print("Type of a = ", typeof(a))
if typeof(a) == String
    x1 = reinterpret(Int64, a)  # 1st attempt
    x1 = parse(Int, a)          # 2nd attempt
else 
    x1 = floor(Int64, a) 
end
print("\nx1 = $x1", ",\t","type of x1 = ", typeof(x1))
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我展示了将字符串转换为类型的函数int,但两者都不起作用。

请建议一个可以将其转换string为的解决方案int,以及是否有任何建议来优化上述代码?

谢谢!

And*_*kin 5

这是使用多重调度的一个很好的例子。您可以定义具有不同行为的多个函数,而不是比较类型(顺便说一句,最好编写a isa String而不是)。typeof(a) == String

myparse(x::Nothing) = nothing
myparse(x::Integer) = x
myparse(x::Real) = Int(round(x))
myparse(x::AbstractString) = myparse(tryparse(Float64, x))
Run Code Online (Sandbox Code Playgroud)

这就是它实际的样子

julia> myparse(1)
1

julia> myparse(1.0)
1

julia> myparse(1.1)
1

julia> myparse("12.3")
12

julia> myparse("asdsad")

Run Code Online (Sandbox Code Playgroud)

在最后一种情况下,它无法解析字符串,因此它只是返回nothing

  • 可以使用“round(Int, x)” (3认同)