clojure - 根据这些值的向量,按地图中的值对地图向量进行排序 - 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
我已经在某处的所有可能值的指定向量对它们进行排序。
怎样才能做到这一点?
解决方案
这允许您这样做
(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})
推荐阅读
- python - 连体模型不学习任何东西,总是将图像编码成一个零向量
- reactjs - ConnectedRouter 在初始渲染时重新加载页面时重定向到“/”
- excel - 循环遍历范围 VBA
- .net - 将新表单添加到项目时未创建 Windows 表单设计器(resx 文件)
- python-3.x - 使用 librosa.resample 后出现“wave.Error:未知格式:3”。librosa 的输出有什么问题吗?
- c# - 为了和并行为了效率
- c# - 表单对话框复制另一个调用它的表单的内容
- c# - 为什么我的实现总是调用同一个派生类?
- jqgrid - jqgrid中的下拉菜单仅在双击时显示
- docker - 如何将 Azure Web 应用程序移动到容器