首页 > 解决方案 > 根据这些值的向量,按地图中的值对地图向量进行排序 - Clojure

问题描述

我们sort-by在 clojure 中可以根据向量或映射对值进行排序。

例如,如果我有一个要排序的向量:

(def ^:const sort-numbers ["one" "two" "three" "four" "five"])

我有这个具有无序值的随机向量,例如:

(def numbers ["two" "three" "one" "four"])

现在,它们可以按以下方式排序:

(sort-by #(.indexOf sort-numbers %) numbers)

同样,现在我有了这个地图向量:

(def numbers-map [{:one 1 :two 2 :three 3} 
                  {:one 4 :two 4 :three 3}
                  {:one 3 :two 2 :three 1}])

如果我想对向量中的所有映射numbers-map按键的值进行排序,:one

(sort-by :one numbers-map)

会做,它会给我以下结果:

({:one 1, :two 2, :three 3} {:one 3, :two 2, :three 1} {:one 4, :two 4, :three 3})

现在,我需要的是这些的组合。也就是说,我需要numbers-map按 key 的值对:one它们进行排序,但我不希望它们被自动排序,而是根据:one我已经在某处的所有可能值的指定向量对它们进行排序。

怎样才能做到这一点?

标签: clojure

解决方案


这允许您这样做

(def numbers-maps [{:one 1 :two 2 :three 3} 
                   {:one 4 :two 4 :three 3}
                   {:one 3 :two 2 :three 1}])

(def sort-numbers [4 3 2 1])

(sort-by #(.indexOf sort-numbers (:one %))
         numbers-maps)

({:one 4, :two 4, :three 3}
 {:one 3, :two 2, :three 1}
 {:one 1, :two 2, :three 3})

这是另一个例子:

(def numbers-maps [{:one 6, :two 9, :three 9}
                   {:one 9, :two 9, :three 8}
                   {:one 7, :two 6, :three 2}
                   {:one 4, :two 4, :three 5}
                   {:one 9, :two 1, :three 5}
                   {:one 1, :two 8, :three 8}
                   {:one 8, :two 3, :three 9}
                   {:one 8, :two 4, :three 5}
                   {:one 4, :two 8, :three 1}
                   {:one 5, :two 1, :three 1}])

(def one-values [10 5 1 2 4 3])

(sort-by #(.indexOf one-values (:one %))
         numbers-maps)

({:one 6, :two 9, :three 9}
 {:one 9, :two 9, :three 8}
 {:one 7, :two 6, :three 2}
 {:one 9, :two 1, :three 5}
 {:one 8, :two 3, :three 9}
 {:one 8, :two 4, :three 5}
 {:one 5, :two 1, :three 1}
 {:one 1, :two 8, :three 8}
 {:one 4, :two 4, :three 5}
 {:one 4, :two 8, :three 1})

推荐阅读