有没有办法将数组转换为整数或浮点数?
Is there a way to turn a array into a integer or float?
我正在尝试将 int 数组更改为 Julia 1.5.4 中的单个 int,如下所示:
x = [1,2,3]
这里我会尝试或使用 code/command(这里:example())
x_new = example(x)
println(x_new)
typeof(x_new)
理想的输出应该是这样的:
123
Int32
我已经尝试使用 parse() 或 push!() 或类似方法解决此问题。但没有什么效果很好。
我找不到类似的问题...
这是你需要的吗?
julia> x = [1,2,3]
3-element Vector{Int64}:
1
2
3
julia> list2int(x) = sum(10 .^ (length(x)-1:-1:0) .* x)
list2int (generic function with 1 method)
julia> list2int(x)
123
您正在寻找字符串连接然后解析:
x_new = parse(Int64, string(x...))
您可以在此处找到有关将此功能添加到 Julia 的问题:https://github.com/JuliaLang/julia/issues/40393
最重要的是,你不想使用字符串,你应该避免不必要的求幂,这两者都会很慢。
一个非常简单的解决方案是
evalpoly(10, reverse([1,2,3]))
拼写多一点,你可以这样做
function joindigits(xs)
val = 0
for x in xs
val = 10*val + x
end
return val
end
另一种将许多小数字转换为更大数字的有趣方法是合并原始字节:
julia> reinterpret(Int16, [Int8(2),Int8(3)])
1-element reinterpret(Int16, ::Vector{Int8}):
770
注意 770 = 256*3 + 2
或实际 Int
s:
julia> reinterpret(Int128, [10,1])
1-element reinterpret(Int128, ::Vector{Int64}):
18446744073709551626
(注意结果正好是 Int128(2)^64+10
)
我正在尝试将 int 数组更改为 Julia 1.5.4 中的单个 int,如下所示:
x = [1,2,3]
这里我会尝试或使用 code/command(这里:example())
x_new = example(x)
println(x_new)
typeof(x_new)
理想的输出应该是这样的:
123
Int32
我已经尝试使用 parse() 或 push!() 或类似方法解决此问题。但没有什么效果很好。 我找不到类似的问题...
这是你需要的吗?
julia> x = [1,2,3]
3-element Vector{Int64}:
1
2
3
julia> list2int(x) = sum(10 .^ (length(x)-1:-1:0) .* x)
list2int (generic function with 1 method)
julia> list2int(x)
123
您正在寻找字符串连接然后解析:
x_new = parse(Int64, string(x...))
您可以在此处找到有关将此功能添加到 Julia 的问题:https://github.com/JuliaLang/julia/issues/40393
最重要的是,你不想使用字符串,你应该避免不必要的求幂,这两者都会很慢。
一个非常简单的解决方案是
evalpoly(10, reverse([1,2,3]))
拼写多一点,你可以这样做
function joindigits(xs)
val = 0
for x in xs
val = 10*val + x
end
return val
end
另一种将许多小数字转换为更大数字的有趣方法是合并原始字节:
julia> reinterpret(Int16, [Int8(2),Int8(3)])
1-element reinterpret(Int16, ::Vector{Int8}):
770
注意 770 = 256*3 + 2
或实际 Int
s:
julia> reinterpret(Int128, [10,1])
1-element reinterpret(Int128, ::Vector{Int64}):
18446744073709551626
(注意结果正好是 Int128(2)^64+10
)