简体   繁体   English

如何在 julia 中将 Tuple{Array{Float64,1},Array{Float64,1}} 转换为 Array{Tuple{Float64,Float64},1}

[英]How to convert a Tuple{Array{Float64,1},Array{Float64,1}} to Array{Tuple{Float64,Float64},1} in julia

How may I convert a Tuple{Array{Float64,1},Array{Float64,1}} to Array{Tuple{Float64,Float64},1} ?如何将Tuple{Array{Float64,1},Array{Float64,1}}转换为Array{Tuple{Float64,Float64},1}

Code代码

#Sampling
function sam()
    x = range(0, 10.0, length = 9) |> collect
    y = range(0, 10.0, length = 9) |> collect
    return (x,y)
end
xy = sam()
typeof(xy)

The code above returns this output:上面的代码返回这个 output:

Tuple{Array{Float64,1},Array{Float64,1}}

The easiest thing to do in your situation is to assign the output of your function to two separate variables, like this:在您的情况下,最简单的方法是将 function 的 output 分配给两个单独的变量,如下所示:

function foo()
    x = [1, 2, 3]
    y = [4, 5, 6]
    return x, y
end

x, y = foo()

See the docs on multiple return values. 请参阅有关多个返回值的文档。

Then you can use zip to turn the vectors into an iterator of tuples:然后您可以使用zip将向量转换为元组的迭代器:

julia> x, y = foo()
([1, 2, 3], [4, 5, 6])

julia> x
3-element Array{Int64,1}:
 1
 2
 3

julia> y
3-element Array{Int64,1}:
 4
 5
 6

julia> z = zip(x, y)
zip([1, 2, 3], [4, 5, 6])

Note that the output of zip is an iterator, rather than an array of tuples.请注意,zip 的zip是一个迭代器,而不是一个元组数组。 You can either iterate through the elements of the iterator to get the individual tuples,您可以遍历迭代器的元素以获取单个元组,

julia> foreach(println, z)
(1, 4)
(2, 5)
(3, 6)

or you can collect the iterator if you actually need an array of tuples:或者,如果您确实需要一个元组数组,则可以收集迭代器:

julia> collect(z)
3-element Array{Tuple{Int64,Int64},1}:
 (1, 4)
 (2, 5)
 (3, 6)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM