clojure过滤器嵌套地图以基于内部地图值返回键 [英] clojure filter nested map to return keys based on inner map values
问题描述
对于这个称为表格"的嵌套地图,
For this nested map called "tables",
(def tables
{:tableA {:occupied false :party nil}
:tableB {:occupied true :party nil}
:tableC {:occupied false :party nil}})
如何过滤并获取:occupied = false的键?
how do I filter and get back the keys where :occupied = false ?
正确结果应为(:tableA :tableC)
我可以使用过滤器" HOF来做到这一点吗?我应该使用列表理解吗?
can I do this with "filter" HOF? Should I be using a list comprehension?
推荐答案
使用keep
可以很容易地做到这一点:
You could do it pretty easily with keep
:
(keep (fn [[k v]] (if-not (:occupied v) k)) tables)
但是,正如您所观察到的,在映射/过滤序列时,尤其是在处理嵌套序列时,使用for
通常是一个很好的解决方案.
However, as you observed, using for
is often a good solution whenever you're mapping / filtering sequences, especially if you're dealing with nested sequences.
(for [[k v] tables :when (not (:occupied v))] k)
我通常更喜欢使用for
,尤其是当我想对目标项目使用解构时.在这种情况下,解构非常适合将键/值对与[k v]
绑定.
I usually prefer using for
, especially when I want to use destructuring on the target items. In this case, destructuring is nice for binding the key/value pair with [k v]
.
这篇关于clojure过滤器嵌套地图以基于内部地图值返回键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!