在地图中反向查找

Isu*_*uru 10 clojure map key-value

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

Eri*_*son 25

我认为这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.
Run Code Online (Sandbox Code Playgroud)


mik*_*era 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
Run Code Online (Sandbox Code Playgroud)


jbe*_*ear 3

尝试

(some #(if (= (val %) your-val) (key %)) your-map) 
Run Code Online (Sandbox Code Playgroud)