我有这个结构(它是解析 JSON 响应的结果):
[{"a" {"b" 1 "c" 2}
"children" [{"a" {"b" 3 "c" 4} "children" []}]}
{"a" {"b" 5 "c" 6} "children" []}
{"a" {"b" 7 "c" 8}
"children" [{"a" {"b" 9 "c" 10} "children" []}]}]
所以它是一棵树。 children
是节点向量。每个节点都是一个包含a、b 和子节点
的映射。
我正在尝试查找其 b
属性值为 9
的节点。
所以,查找的结果是:
我尝试使用tree-seq
遍历结构:
(tree-seq #(not-empty? % "children") identity structure)
但实际上我得到了相同的结构。我期望获得一系列节点,其中关系被展平,然后我可以对该序列进行过滤。
如何以惯用的方式做到这一点(并且希望是高性能的)?随意用 zipper 或步行让我大吃一惊。
最佳答案
您可以像这样获得所需的树序列:
(def ts (mapcat (partial tree-seq #(contains? % "children")
#(get % "children"))
your-data-structure))
mapcat
是必需的,因为您的输入数据结构包含多个根节点。
E. G。找到一个像这样的节点:
(first (filter #(= (get-in % ["a" "b"]) 9) ts))
;-> {"a" {"b" 9, "c" 10}, "children" []}
关于clojure - 如何在深度嵌套的数据结构中查找元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32103459/