【问题标题】:Convert array of type either float or strings to int type in Julia (Replicating int() from Python)在 Julia 中将浮点或字符串类型的数组转换为 int 类型(从 Python 复制 int())
【发布时间】:2021-03-18 07:12:08
【问题描述】:

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

参考: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))

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

请提出一个可以将string 转换为int 的解决方案以及优化上述代码的任何建议?

谢谢!

【问题讨论】:

  • 由于a = "5.9" 不是 Int 类型,您应该尝试将其解析为例如。首先使用 Float64,然后应用适当的舍入函数,如下所示:Int(round(parse(Float64, "5.9")))
  • 在 python 中(请参阅您的参考链接)'int' 不适用于“5.9”并给出以下错误。 ValueError: int() 以 10 为底的无效文字:'5.9'
  • @mapi1 感谢您的建议,现在可以使用了!!!非常感谢!!
  • @callmeSteve 是的,同意,python 中的int 不能转换 float-type string 它只适用于 int-type string 即@987654333 @.

标签: string type-conversion integer julia


【解决方案1】:

这是一个很好的例子来玩多分派。不用比较类型(顺便说一句,最好写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))

这就是它在行动中的样子

julia> myparse(1)
1

julia> myparse(1.0)
1

julia> myparse(1.1)
1

julia> myparse("12.3")
12

julia> myparse("asdsad")

在最后一种情况下它不能解析字符串,所以它只返回nothing

【讨论】:

  • 可以使用round(Int, x)
  • @DNF 他绝对应该使用它!
  • @DNF 感谢您的建议,但直接使用 round() 会返回最接近的整数,例如 -> round(Int, 5.3) = 5` 而 round(Int, 5.7) = 6 。我想要的是它只返回真正的整数而不考虑它的十进制值。
  • @AndrejOskin 感谢您的回复,我没有想到这种方法。惊人的建议!!!!我将尝试使用这种方法。非常感谢!
  • @PrzemyslawSzufel 感谢您的回复,我尝试使用round() 功能,但由于@DNF 回复中提到的原因,我无法继续使用该功能。但是如果有解决方法请分享,非常感谢!
【解决方案2】:

更短的形式:

myparse(x::Real) = trunc(Int, x)
myparse(::Nothing) = nothing
myparse(x::AbstractString) = myparse(tryparse(Float64, x))

trunc 去掉浮点数,只剩下整数部分,例如:

julia> myparse("-4.7")
-4

【讨论】:

  • 感谢您的建议,这太棒了,非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
相关资源
最近更新 更多