【问题标题】:Sorting array of struct in Julia在 Julia 中对结构数组进行排序
【发布时间】:2022-01-05 14:59:27
【问题描述】:

假设我在 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. 

请帮忙。

【问题讨论】:

    标签: sorting struct julia


    【解决方案1】:

    在 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函数是很好的风格。

    【讨论】:

    • 非常感谢!你拯救了我的一天。
    猜你喜欢
    • 2016-06-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2014-03-12
    • 2016-07-14
    相关资源
    最近更新 更多