julia-lang – Julia:将数字字符串转换为float或int

前端之家收集整理的这篇文章主要介绍了julia-lang – Julia:将数字字符串转换为float或int前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将从数据库中拉出的数值数据写入Float64 [].原始数据是:: ASCIIString格式,所以尝试将其推送到数组给出以下错误
julia> push!(a,"1")
ERROR: MethodError: `convert` has no method matching convert(::Type{Float64},::ASCIIString)
This may have arisen from a call to the constructor Float64(...),since type constructors fall back to convert methods.
Closest candidates are:
  call{T}(::Type{T},::Any)
  convert(::Type{Float64},::Int8)
  convert(::Type{Float64},::Int16)
  ...
 in push! at array.jl:432

尝试直接转换数据不出意料地引发同样的错误

julia> convert(Float64,::Int16)
  ...

鉴于我知道数据是数字的,有没有一种方法可以在推送之前进行转换?

附:我正在使用版本0.4.0

解决方法

您可以从字符串中解析(Float64,“1”).或者在矢量的情况下
map(x->parse(Float64,x),stringvec)

将解析整个向量.

BTW考虑使用tryparse(Float64,x)而不是解析.它返回一个Nullable {Float64},这是null,在这种情况下,字符串不能很好地解析.例如:

isnull(tryparse(Float64,"33.2.1")) == true

并且通常会有一个默认值,以防解析错误

strvec = ["1.2","NA","-1e3"]
map(x->(v = tryparse(Float64,x); isnull(v) ? 0.0 : get(v)),strvec)
# gives [1.2,0.0,-1000.0]
原文链接:https://www.f2er.com/css/216496.html

猜你在找的CSS相关文章