Julia python equivalents list approach

I just started messing with Julia, and I really like it. However, I run to the road block. For example, in Python (although not very efficient or pythonic), I would create an empty list and add a list of known sizes and types, and then convert to a NumPy array:

Python snippet

a = [] for .... a.append([1.,2.,3.,4.]) b = numpy.array(a) 

I want to be able to do something like this in Julia, but I can't figure it out. This is what I have so far:

fragment of Julia

 a = Array{Float64}[] for ..... push!(a,[1.,2.,3.,4.]) end 

The result is an n-element Array{Array{Float64,N},1} size (n,), but I would like it to be nx4 Array{Float64,2} .

Any suggestions or a better way to do this?

+6
source share
2 answers

A literal translation of your code will be

 # Building up as rows a = [1. 2. 3. 4.] for i in 1:3 a = vcat(a, [1. 2. 3. 4.]) end # Building up as columns b = [1.,2.,3.,4.] for i in 1:3 b = hcat(b, [1.,2.,3.,4.]) end 

But this is not a natural picture in Julia, you would do something like

 A = zeros(4,4) for i in 1:4, j in 1:4 A[i,j] = j end 

or even

 A = Float64[j for i in 1:4, j in 1:4] 

Basically allocates all the memory at once.

+4
source

Does it do what you want?

 julia> a = Array{Float64}[] 0-element Array{Array{Float64,N},1} julia> for i=1:3 push!(a,[1.,2.,3.,4.]) end julia> a 3-element Array{Array{Float64,N},1}: [1.0,2.0,3.0,4.0] [1.0,2.0,3.0,4.0] [1.0,2.0,3.0,4.0] julia> b = hcat(a...)' 3x4 Array{Float64,2}: 1.0 2.0 3.0 4.0 1.0 2.0 3.0 4.0 1.0 2.0 3.0 4.0 

It seems to match python output:

 In [9]: a = [] In [10]: for i in range(3): a.append([1, 2, 3, 4]) ....: In [11]: b = numpy.array(a); b Out[11]: array([[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3, 4]]) 

I should add that this is probably not what you really want to do, since hcat(a...)' can be expensive if a has many elements. Is there a reason not to use a 2d array from the start? Perhaps there is more context to the question (i.e. the Code you are actually trying to write).

+4
source

Source: https://habr.com/ru/post/981856/


All Articles