简体   繁体   English

Clojure 按值获取映射键

[英]Clojure get map key by value

I'm a new clojure programmer.我是一名新的 clojure 程序员。

Given...鉴于...

{:foo "bar"}

Is there a way to retrieve the name of the key with a value "bar"?有没有办法用值“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!帮助表示赞赏!

There can be multiple key/value pairs with value "bar".可以有多个值为“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)

Or要么

(filter (comp #{"bar"} hm) (keys hm))

Or要么

(reduce-kv (fn [acc k v]
             (if (= v "bar")
               (conj acc k)
               acc))
           #{} hm)

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如果您知道您的 vals 彼此不同,您还可以创建一个反向查找哈希映射

(clojure.set/map-invert hm)
user> (->> {:a "bar" :b "foo" :c "bar" :d "baz"} ; initial map
           (group-by val)   ; sorted into a new map based on value of each key
           (#(get % "bar")) ; extract the entries that had value "bar"
           (map key))     ; get the keys that had value bar
(:a :c)

As in many other cases you can use for:与许多其他情况一样,您可以用于:

(def hm {:foo "bar"})
(for [[k v] hm :when (= v "bar")] k)

And with "some" you can return the first matching item instead of a list (as probably the original question implied):使用“some”,您可以返回第一个匹配项而不是列表(可能是原始问题所暗示的):

(some (fn [[k v]] (if (= v "bar") k)) hm)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM