gpt4 book ai didi

clojure - 如何在 Clojure 中重新排序 map ?

转载 作者:行者123 更新时间:2023-12-03 00:25:41 26 4
gpt4 key购买 nike

我有一个像这样的有序 map :

{:a 1 :b 2 :c 3}

:并给出一个排序列表,例如:

[:c :a]

:我想找到最简单的方法来获得:

{c: 3 :a 1}

:有谁知道怎么做吗?

更新:

(defn asort [amap order]  (conj {} (select-keys amap order)))

(asort {:a 1 :b 2 :c 3} [:c :a] )

最佳答案

我可能会将排序向量转换为 HashMap 以快速查找排序索引,结果如下:

{ :c 0  :a 1 }

有几种方法可以从 seq/向量自动执行此操作(例如使用 range 进行 map,然后将 reduce 转换为 {}与assoc)。将其结果(或上面的文字映射)绑定(bind)到本地(使用 let),我们将其称为 order-map

然后过滤原始 map (m)的条目,仅包含排序中包含的条目:

(select-keys m order)

并使用如下比较器函数将过滤表达式的结果放回到新的排序映射中(使用sorted-map-by):

(fn [a b] (compare (order-map a) (order-map b)))

请注意,如果您实际上并不需要将其作为映射,并且可以使用序列,则可以将 sort-by 与使用相同 order-map 的键函数一起使用。

把这些放在一起,你会得到:

(defn asort [m order]
(let [order-map (apply hash-map (interleave order (range)))]
(conj
(sorted-map-by #(compare (order-map %1) (order-map %2))) ; empty map with the desired ordering
(select-keys m order))))

还有:

=> (asort (apply sorted-map (interleave (range 0 50) (range 0 50))) (range 32 0 -1))
{32 32, 31 31, 30 30, 29 29, 28 28, 27 27, 26 26, 25 25, 24 24, 23 23, 22 22, 21 21, 20 20, 19 19, 18 18, 17 17, 16 16, 15 15, 14 14, 13 13, 12 12, 11 11, 10 10, 9 9, 8 8, 7 7, 6 6, 5 5, 4 4, 3 3, 2 2, 1 1}

关于clojure - 如何在 Clojure 中重新排序 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5430557/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com