Clojure 按值获取映射键 [英] Clojure get map key by value

查看:20
本文介绍了Clojure 按值获取映射键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新的 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆