dictionary - Clojure - 在最内层过滤嵌套映射

标签 dictionary filter clojure

过滤以下嵌套映射并保持嵌套映射结构的最佳方法是什么。在我的示例中,Alice 和 Bob 可以重复,例如同一名员工可以同时在几个不同的工厂工作。

(def universe
  {:customer1
    {:plant1
      { "Alice" {:age 35 :sex "F"}
        "Bob" {:age 25 :sex "M"}}
     :plant2 {}} 
   :customer2 {}
  })

例如,我想按年龄 >30 进行过滤并返回相同的 map 结构。理想情况下,这适用于任何嵌套 map 深度,在最内层进行过滤。预期结果:

(def universe
  {:customer1
    {:plant1
      { "Alice" {:age 35 :sex "F"}
        }
     :plant2 {}} 
   :customer2 {}
  })

我看过clojure filter nested map to return keys based on inner map values但它看起来并没有解决我的问题。谢谢,

最佳答案

这与之前的问题之一非常相似:

(use '[com.rpl.specter])
(let [input          {:customer1
                                 {:plant1
                                          {"Alice" {:age 35 :sex "F"}
                                           "Bob"   {:age 25 :sex "M"}}
                                  :plant2 {}}
                      :customer2 {}}
      desired-output {:customer1
                                 {:plant1 {"Alice" {:age 35 :sex "F"}}
                                  :plant2 {}}
                      :customer2 {}}
      RECUR-MAP      (recursive-path [] p (cond-path map? (continue-then-stay [MAP-VALS p])))]

    (clojure.test/is (= (setval [RECUR-MAP (pred :age) #(> 30 (:age %))] NONE input)
                        desired-output)))

关于dictionary - Clojure - 在最内层过滤嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54143713/

相关文章:

c# - 从 Dictionary<string, string> 获取第一个键

Clojure 平面序列到树中

amazon-web-services - "The conditional request failed"而条件有效

clojure - :fin being used? 怎么样

python defaultdict 如何在不创建 key 的情况下检查嵌套 key 是否存在或是否为 []

c++ - std::shared_ptr 的 std::map 中的线程安全

python - 使用类函数更新字典

algorithm - 图像编辑软件中滤镜背后使用的算法是什么?

Javascript 使用单选按钮过滤 html 元素的可见性

javascript - 使用 forEach 过滤数组