在地图中反向查找

时间:2012-05-16 04:38:36

标签: map clojure key-value

我必须使用值从地图中提取密钥。除了自己实现反向查找之外,有没有办法做到这一点?

6 个答案:

答案 0 :(得分:25)

我认为map-invert是执行此操作的正确方法。

From the docs:

;; Despite being in clojure.set, this has nothing to do with sets. 

user=> (map-invert {:a 1, :b 2})
{2 :b, 1 :a}

;; If there are duplicate keys, one is chosen:

user=> (map-invert {:a 1, :b 1})
{1 :b}

;; I suspect it'd be unwise to depend on which key survives the clash.

答案 1 :(得分:6)

您可以使用2行功能轻松地反转地图:

(defn reverse-map [m]
  (into {} (map (fn [[a b]] [b a]) m)))

(def a {:a 1 :b 2 :c 3})

(reverse-map a)
=> {1 :a, 3 :c, 2 :b}

((reverse-map a) 1)
=> :a

答案 2 :(得分:3)

尝试

(some #(if (= (val %) your-val) (key %)) your-map) 

答案 3 :(得分:2)

如果您使用的是ClojureScript,或者还需要一个替代方案:)

root

答案 4 :(得分:0)

另一个:

(defn reverse-map [m]                                                                                                                          
  (apply hash-map  (mapcat reverse m)))  

(defn reverse-lookup [m k]                                                                                                                     
  (ffirst (filter (comp #{k} second) m)))   

答案 5 :(得分:0)

如果你想保留按键,最好只是反转地图,但是在集合/列表等中收集旧密钥......

(defn map-inverse [m]
  (reduce (fn [m' [k v]] (update m' v clojure.set/union #{k})) {} m))

(defn map-inverse [m]
  (reduce (fn [m' [k v]] (update m' v conj k)) {} m))