Julia 中的结构数组排序

sto*_*ner 1 sorting struct julia

假设我在 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 
Run Code Online (Sandbox Code Playgroud)

现在我想根据收入值对总体进行排序。Julia 有什么办法可以实现这一目标吗?如果我用 Python 来做的话,会是这样的:

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

请帮忙。

phi*_*ler 5

Julia 中有一系列排序函数。关键函数是sort(对应Python的sorted) 和sort!(对应Python的list.sort)。

与 Python 中一样,它们有几个关键字参数,其中之一是by,对应于key

因此翻译为

sorted(population, key = lambda x: x.Revenue)
Run Code Online (Sandbox Code Playgroud)

将会

getrevenue(e::emptys) = e.Revenue
sort(population, by=getrevenue)
Run Code Online (Sandbox Code Playgroud)

或者e -> e.Revenue,但无论如何,拥有 getter 函数都是很好的风格。