假設我在 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
現在我想根據收入值對這個人口進行排序。朱莉婭有什么辦法可以做到這一點?如果我要在 Python 中執行此操作,它將是這樣的:
sorted(population, key = lambda x: x.Revenue) # The population in Python can be prepared using https://pypi.org/project/ypstruct/ library.
請幫忙。
uj5u.com熱心網友回復:
Julia 中有一系列的排序功能。關鍵函式是sort(對應Python的sorted)和sort!(對應Python的list.sort)。
和在 Python 中一樣,它們有幾個關鍵字引數,其中一個是by,對應于key。
因此翻譯
sorted(population, key = lambda x: x.Revenue)
將是
getrevenue(e::emptys) = e.Revenue
sort(population, by=getrevenue)
或者e -> e.Revenue,但無論如何,擁有一個 getter 函式是一種很好的風格。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/405597.html
標籤:
