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

查看:122
本文介绍了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"?

我浏览了地图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屋!

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