排序嵌套地图Clojure

时间:2015-09-21 14:13:31

标签: clojure

我正在尝试按键值对地图进行排序。鉴于这张地图:

{:1 {:bar "something" :rank 10} :2 {:bar "other" :rank 20}}

我喜欢按rank值对其进行排序:

{:2 {:bar "other" :rank 20} :1 {:bar "something" :rank 10} }

可以使用sort-by

提前致谢

4 个答案:

答案 0 :(得分:2)

这与sort-by一样简单,但由于按升序排序,您必须使用reverse让它以正确的方式运行。< / p>

(reverse
    (sort-by (comp :rank second)
        {:1 {:bar "something" :rank 10} :2 {:bar "other" :rank 20}}))

答案 1 :(得分:2)

sort-by采用关键功能以及可选的自定义比较器

;              keyfn         comparator
(sort-by (comp :rank second) > 
  {:1 {:bar "something" :rank 10} :2 {:bar "other" :rank 20}})
;=> ([:2 {:bar "other", :rank 20}] [:1 {:bar "something", :rank 10}])

答案 2 :(得分:2)

其他答案可行,但如果您要执行此命令,那么最好将数据存储在data.priority-map中。它专为这种情况而设计。

  

优先级映射与有序映射非常相似,但是有序映射生成按键排序的条目序列,优先级映射生成按值排序的条目。

; You'll need to add [org.clojure/data.priority-map "0.0.7"] to :dependencies first

user=> (require '[clojure.data.priority-map :as pm])
; nil
user=> (pm/priority-map-keyfn-by :rank > :1 {:bar "something" :rank 10} :2 {:bar "other" :rank 20})
; {:2 {:rank 20, :bar "other"}, :1 {:rank 10, :bar "something"}}

答案 3 :(得分:1)

另见this answer

升序:

user=> (sort-by (comp :rank second) < {:1 {:bar "something" :rank 10} :2 {:bar "other" :rank 20} :3 {:bar "bar" :rank 15}})
([:1 {:bar "something", :rank 10}] [:3 {:bar "bar", :rank 15}] [:2 {:bar "other", :rank 20}])

降序:

user=> (sort-by (comp :rank second) > {:1 {:bar "something" :rank 10} :2 {:bar "other" :rank 20} :3 {:bar "bar" :rank 15}})
([:2 {:bar "other", :rank 20}] [:3 {:bar "bar", :rank 15}] [:1 {:bar "something", :rank 10}])

这两个都返回map的元素序列,再次转换回地图,将其包装在(into {} ...)