11

我必须使用一个值从地图中提取一个键。除了自己实现反向查找之外,还有其他方法吗?

4

6 回答 6

26

我认为这map-invert是正确的做法。

从文档:

;; 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.
于 2012-10-26T01:32:07.837 回答
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
于 2012-05-16T04:49:42.550 回答
3

尝试

(some #(if (= (val %) your-val) (key %)) your-map) 
于 2012-05-16T06:46:45.247 回答
2

如果您正在使用 ClojureScript 或者您需要另一种选择:)

(zipmap (vals m) (keys m))

于 2015-08-12T09:43:31.557 回答
0

另一个:

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

(defn reverse-lookup [m k]                                                                                                                     
  (ffirst (filter (comp #{k} second) m)))   
于 2012-06-08T21:18:25.940 回答
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))
于 2017-03-13T19:22:23.690 回答