【问题标题】:cycle through a lazy sequence of maps and change one of the values in one of the maps循环遍历一系列惰性映射并更改其中一个映射中的一个值
【发布时间】:2021-06-29 18:53:24
【问题描述】:

我有一些地图的惰性序列。
我想循环浏览每张地图并执行以下操作:
if (= :b "this one") 然后将 :c 更改为 99。

({:a 1
  :b "this one"
  :c 100}
 {:a "A"
  :c "Q"
  :z "Z"})

【问题讨论】:

  • 这样的事情会做:(mapv #(cond-> % (= "this one" (:b %)) (update :c dec)) data) => [{:a 1, :b "this one", :c 99} {:a "A", :c "Q", :z "Z"}]

标签: clojure


【解决方案1】:
(map #(if (= (:b %) "this one") (assoc % :c 99) %) data)

【讨论】:

    【解决方案2】:

    这是一种方法:

    (ns tst.demo.core
      (:use tupelo.core tupelo.test))
    
    (dotest
      (let [data   [{:a 1
                     :b "this one"
                     :c 100}
                    {:a "A"
                     :c "Q"
                     :z "Z"}]
            result (vec (for [curr-map data]
                          (if (= "this one" (:b curr-map))
                            (assoc curr-map :c 99)
                            curr-map)))]
        (is= result
          [{:a 1, :b "this one", :c 99}
           {:a "A", :c "Q", :z "Z"}])))
    
    

    基于my favorite template project。请参阅list of documentation sources,尤其是。 Clojure CheatSheet 和 Getting Clojure

    等书籍

    【讨论】:

    • 我会喜欢的,但是我怎样才能把 ({:a 1...) 变成一个向量呢?
    • 只需使用(vec <some collection>),或将其写为文字。此外,答案仍然适用于您的原始地图列表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    相关资源
    最近更新 更多