Clojure按值获取映射关键字 [英] Clojure get map key by value
问题描述
我是一个新的clojure程序员。
I'm a new clojure programmer.
给定...
{:foo "bar"}
是否有办法检索键和值bar?
Is there a way to retrieve the name of the key with a value "bar"?
我浏览了地图docs,可以看到一种方式来检索键和值或只是值,但不只是键。帮助赞赏!
I've looked through the map docs and can see a way to retrieve key and value or just value but not just the key. Help appreciated!
推荐答案
可以有多个键/值对,值为bar。这些值不是用于查找的哈希,与它们的键相反。根据你想要实现什么,你可以用一个线性算法来查找键:
There can be multiple key/value pairs with value "bar". The values are not hashed for lookup, contrarily to their keys. Depending on what you want to achieve, you can look up the key with a linear algorithm like:
(def hm {:foo "bar"})
(keep #(when (= (val %) "bar")
(key %)) hm)
或
(filter (comp #{"bar"} hm) (keys hm))
或
(reduce-kv (fn [acc k v]
(if (= v "bar")
(conj acc k)
acc))
#{} hm)
这将返回一系列键。如果你知道你的val是彼此不同,你也可以创建一个反向查找哈希映射与
which will return a seq of keys. If you know that your vals are distinct from each other, you can also create a reverse-lookup hash-map with
(clojure.set/map-invert hm)
这篇关于Clojure按值获取映射关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!