Home > other >  Sorting array of struct in Julia
Sorting array of struct in Julia

Time:01-07

Suppose if I have the following in Julia:

mutable struct emptys
    begin_time::Dict{Float64,Float64}; finish_time::Dict{Float64,Float64}; Revenue::Float64
end
population = [emptys(Dict(),Dict(),-Inf) for i in 1:n_pop] #n_pop is a large positive integer value.
for ind in 1:n_pop
    r = rand()
    append!(population[ind].Revenue, r)
    append!(population[ind].begin_time, Dict(r=>cld(r^2,rand())))
    append!(population[ind].finish_time, Dict(r=>r^3/rand()))
 end 

Now I want to sort this population based on the Revenue value. Is there any way for Julia to achieve this? If I were to do it in Python it would be something like this:

sorted(population, key = lambda x: x.Revenue) # The population in Python can be prepared using https://pypi.org/project/ypstruct/ library. 

Please help.

CodePudding user response:

Come on, have you even looked at the docs? But as this has not already been asked on SO as far as I can see, here we go.

There is a whole range of sorting functions in Julia. The key functions are sort (corresponding to Python's sorted) and sort! (corresponding to Python's list.sort).

And as in Python, they have a couple of keyword arguments, one of which is by, corresponding to key.

Hence the translation of

sorted(population, key = lambda x: x.Revenue)

would be

getrevenue(e::emptys) = e.Revenue
sort(population, by=getrevenue)

Or e -> e.Revenue, but having a getter function is good style anyway.

  •  Tags:  
  • Related