在 Julia 中对结构数组进行排序
Sorting array of struct in 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
现在我想根据 Revenue 值对人口进行排序。朱莉娅有什么办法可以实现这一目标吗?如果我要在 Python 中执行它,它将是这样的:
sorted(population, key = lambda x: x.Revenue) # The population in Python can be prepared using https://pypi.org/project/ypstruct/ library.
请帮忙。
Julia 中有完整的 sorting functions 范围。关键函数是sort
(对应Python的sorted
)和sort!
(对应Python的list.sort
)。
和Python一样,他们有一个couple of keyword arguments,其中一个是by
,对应key
。
因此翻译
sorted(population, key = lambda x: x.Revenue)
会是
getrevenue(e::emptys) = e.Revenue
sort(population, by=getrevenue)
或e -> e.Revenue
,但有一个getter功能无论如何都是不错的风格。
假设我在 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
现在我想根据 Revenue 值对人口进行排序。朱莉娅有什么办法可以实现这一目标吗?如果我要在 Python 中执行它,它将是这样的:
sorted(population, key = lambda x: x.Revenue) # The population in Python can be prepared using https://pypi.org/project/ypstruct/ library.
请帮忙。
Julia 中有完整的 sorting functions 范围。关键函数是sort
(对应Python的sorted
)和sort!
(对应Python的list.sort
)。
和Python一样,他们有一个couple of keyword arguments,其中一个是by
,对应key
。
因此翻译
sorted(population, key = lambda x: x.Revenue)
会是
getrevenue(e::emptys) = e.Revenue
sort(population, by=getrevenue)
或e -> e.Revenue
,但有一个getter功能无论如何都是不错的风格。