string Julia:将数字字符串转换为 float 或 int
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33440857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Julia: Convert numeric string to float or int
提问by peter-b
I am trying to write numeric data pulled from a database into a Float64[]
. The original data is in ::ASCIIString
format, so trying to push it to the array gives the following error:
我正在尝试将从数据库中提取的数字数据写入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
Attempting to convert the data directly unsurprisingly throws the same error:
尝试直接转换数据不出所料会引发相同的错误:
julia> convert(Float64, "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)
...
Given that I know the data is numeric, is there a way I can convert it before pushing?
鉴于我知道数据是数字,有没有办法在推送之前转换它?
p.s. I am using version 0.4.0
ps 我使用的是 0.4.0 版
回答by Dan Getz
You can parse(Float64,"1")
from a string. Or in the case of a vector
你可以parse(Float64,"1")
从一个字符串。或者在向量的情况下
map(x->parse(Float64,x),stringvec)
will parse the whole vector.
将解析整个向量。
BTW consider using tryparse(Float64,x)
instead of parse. It returns a Nullable{Float64}
which is null in the case string doesn't parse well. For example:
顺便说一句,考虑使用tryparse(Float64,x)
而不是解析。Nullable{Float64}
在字符串解析不好的情况下,它返回一个空值。例如:
isnull(tryparse(Float64,"33.2.1")) == true
And usually one would want a default value in case of a parse error:
通常人们会想要一个默认值以防解析错误:
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]