我必须使用值从地图中提取密钥。有没有办法做到这一点,而不是自己实施反向查找?在地图中进行反向查找
10
A
回答
3
尝试
(some #(if (= (val %) your-val) (key %)) your-map)
6
你真的可以很容易地逆转地图2线功能:
(defn reverse-map [m]
(into {} (map (fn [[a b]] [b a]) m)))
(def a {:a 1 :b 2 :c 3})
(reverse-map a)
=> {1 :a, 3 :c, 2 :b}
((reverse-map a) 1)
=> :a
0
还有一句:
(defn reverse-map [m]
(apply hash-map (mapcat reverse m)))
(defn reverse-lookup [m k]
(ffirst (filter (comp #{k} second) m)))
25
我认为map-invert
是正确的这样做的方法。
;; Despite being in clojure.set, this has nothing to do with sets.
user=> (map-invert {:a 1, :b 2})
{2 :b, 1 :a}
;; If there are duplicate keys, one is chosen:
user=> (map-invert {:a 1, :b 1})
{1 :b}
;; I suspect it'd be unwise to depend on which key survives the clash.
1
如果您正在使用ClojureScript或者你需要一个比较另类的:)
(zipmap (vals m) (keys m))
0
如果你想保持键
,最好是刚刚反转地图,但收集一套/列表等旧密钥...
(defn map-inverse [m]
(reduce (fn [m' [k v]] (update m' v clojure.set/union #{k})) {} m))
(defn map-inverse [m]
(reduce (fn [m' [k v]] (update m' v conj k)) {} m))
相关问题
- 1. 在Excel中进行反向MATCH查找
- 2. 反向地图查找
- 3. 如何高效地在defaultdict中进行反向查找?
- 4. 使用PHP进行反向IP查找
- 5. 在Ruby中进行反向查找(最好使用Dnsruby)
- 6. CRC-16(IBM)在C++中进行反向查找
- 7. 通过ForeignKey在Tastypie中进行反向查找
- 8. 有没有办法在nhibernate中进行反向查找?
- 9. 在python中使用scapy进行反向dns查找
- 10. 反向查找
- 11. 在Excel中进行双向查找
- 12. 在地图向量中查找对
- 13. 谷歌地图API反向地理编码查找国家
- 14. 从值列表中进行反向DNS查找 - 蟒蛇
- 15. 在Django m2m字段上进行反向查找?
- 16. 无法在Android上进行反向DNS查找
- 17. 使用string_view进行地图查找
- 18. 使用谷歌地图进行反向地理编码
- 19. 使用Google地图进行反向地理编码
- 20. 反向查找JComboBox
- 21. 反向查找表
- 22. 如何在地图中使用rewritecond进行查找
- 23. EXCEL - 在矩阵中反向查找
- 24. 反向在字符串中查找
- 25. 在字符串中反向查找Python
- 26. prefetch_related()在Django中的ForeignKey反向查找?
- 27. 在CakePHP中反向查找('线程')?
- 28. 具有多个查找字段的其他调用进行反向查找
- 29. 在模板中的两个应用程序之间进行反向ForeignKey查找
- 30. 是否可以在InnoDB表中使用Mysql外键进行反向查找?
什么我f 2或更多的键具有相同的值?你只需要其中一个,还是全部? – ivant