目标:
我需要一个像 (Float, string, int, string, int, string, int, ...) 这样的元组。
由于我在程序过程中计算条目,因此我首先将它们添加到数组/向量中。
尝试:
my_array = []
append!(my_array, 0.1)
append!(my_array, "ab")
append!(my_array, 2)
println(tuple(my_array...))
# Bad output
(0.1, 'a', 'b', 2)
问题:
我怎样才能得到
# Good output
(0.1, "ab", 2)
相反?
最佳答案
问题不在于元组构造,而是对 append!
的明显误解:
julia> append!(my_array, 0.1)
1-element Vector{Any}:
0.1
julia> append!(my_array, "ab")
3-element Vector{Any}:
0.1
'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)
'b': ASCII/Unicode U+0062 (category Ll: Letter, lowercase)
append!
将任何可迭代的元素(其中包含标量数字)单独附加到数组中。字符串是字符的可迭代对象。
相反,使用push!
:
julia> my_array2 = []
Any[]
julia> push!(my_array2, 0.1)
1-element Vector{Any}:
0.1
julia> push!(my_array2, "ab")
2-element Vector{Any}:
0.1
"ab"
julia> push!(my_array2, 2)
3-element Vector{Any}:
0.1
"ab"
2
julia> Tuple(my_array2)
(0.1, "ab", 2)
(不幸的是,这与 Python 中的 append
和 extend
不一致......但你已经习惯了。)
关于arrays - 附加!将字符串切成字符,推!不[ Julia ],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72359994/