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"?
我浏览了地图文档,可以看到一种检索键和值或仅检索值而不只是检索键的方法.感谢帮助!
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屋!