朱莉娅:对类型的字典进行排序 [英] Julia: Sorting a dict of types

查看:92
本文介绍了朱莉娅:对类型的字典进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个充满工作类型的字典

I have a dict filled with Job types

一个工作有一个名称(字符串)和一个分数(int)

A job has a name(string) and a score(int)

我设法将作业加载到Dict中,并且我想根据作业得分使用Sort方法对它们进行排序。但是,当我对字典进行排序(称为工作)时,它给了我一个新的分数排序向量。

I managed to load the jobs into a Dict, and I want to sort them using the Sort method based on the jobs scores. However, when I sort the dict (call it jobs), it gives me a new vector of the sorted scores.

有什么方法可以对字典进行排序,同时保留作业有特定分数吗?

is there any way to sort the dict while preserving which job has its specific score?

jobs = Dict([(nurse, nurse.score), (construction, construction.score),
           (programmer, programmer.score), (retail, retail.score)])

sort(collect(values(jobs)))

因此,如果我的护士得分为3,程序员的得分为6,零售的得分为0,建筑的得分为4,我希望输出是包含以下内容的字典(或类似内容):

so if I have nurse with a score of 3, programmer with a score of 6, retail with a score of 0, and construction with a score of 4, I would want the output to be a dict (or something similar) that would contain:


  1. programmer,6

  2. 建筑,4

  3. 护士,3

  4. 零售,0

  1. programmer, 6
  2. construction, 4
  3. nurse, 3
  4. retail, 0

,或者甚至更好,我是否可以按值对它进行排序,但仅将作业作为矢量获得输出?然后在我的代码中稍后引用该向量?

or, even better, could I sort it by the values but get the output as a vector with just the jobs? then reference that vector later in my code?

推荐答案

这在您的特定情况下有效:

this works in your specific case:

jobs = Dict("nurse"=>3, "construction"=>4, "programmer"=>6, "retail"=>0)
jobpairs = collect(jobs)
jobvalues = collect(values(jobs))
sind = sort(collect(values(jobs)), rev=true)

julia> sortedNames = [jobpairs[i] for i in indexin(sind, jobvalues)]
4-element Array{Any,1}:
 "programmer"=>6  
 "construction"=>4
 "nurse"=>3       
 "retail"=>0    

如果两个关键字具有相同的值,我们需要做更多工作来处理索引。

如马特在下面的评论中建议的,我们应该使用 sortperm 而不是 indexin ,如果

as Matt suggested in the comment below, we should use sortperm rather than indexin which won't work if the dict has at least two keywords that have the same value.

jobs = Dict("nurse"=>3, "construction"=>4, "foo"=>3, "programmer"=>6, "retail"=>0) 
jobpairs = collect(jobs)
jobvalues = collect(values(jobs))
sind = sortperm(collect(values(jobs)), rev=true)

julia> sortedNames = [jobpairs[i].first for i in sind]
5-element Array{Any,1}:
 "programmer"  
 "construction"
 "foo"        
 "nurse"       
 "retail"     

这篇关于朱莉娅:对类型的字典进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆