如何在Clojure中重新排序地图? [英] How to reorder a map in Clojure?

查看:46
本文介绍了如何在Clojure中重新排序地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的有序地图:

I have an ordered map like so:

{:a 1 :b 2 :c 3}

:并给出以下订单列表:

: and given a list of orderings like :

[:c :a]

:我想找到最简单的方法:

: I would like to find the simplest way possible to get :

{c: 3 :a 1}

:有人知道怎么做吗?

更新:

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

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


推荐答案

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

I would probably convert the vector of orderings into a hash map to quickly look up the ordering index, resulting in something like this:

{ :c 0  :a 1 }

有几种自动执行此操作的方法从seq / vector(例如 map 中具有 range ,然后 reduce 放入带有 assoc 的{})。将结果(或上面的文字映射)绑定到本地(使用 let ),我们称之为 order-map

There are a few ways to do that automatically from a seq/vector (e.g. map with range, then reduce into a {} with assoc). Bind the result of that (or the literal map above) to a local (with let), let's call it order-map.

然后过滤原始地图(m)的条目以仅包括订购中包含的条目:

Then filter the entries of the original map (m) to only include the ones included in the ordering:

(select-keys m order)

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

And put the result of that filtered expression back into a new sorted map (using sorted-map-by), using a comparator function like the following:

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

请注意,如果实际上并不需要将其用作地图,并且可以使用序列,则可以使用 sort-by 具有使用相同顺序图的键函数。

Note that if you didn't actually need it as a map, and a sequence will do, you can use sort-by with a key function that uses the same order-map.

将其放在一起,您将得到:

Putting this together, you get:

(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中重新排序地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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