简体   繁体   English

Clojure:将函数应用于地图向量中的地图中的每个值

[英]Clojure: applyng function on every value in a map in vector of maps

How to apply a function on every value in a map in vector of maps. 如何对地图向量中的地图中的每个值应用函数。

If I have a vector of maps 如果我有地图矢量

(def vector-of-maps [{:a 1 :b 2} {:a 3 :b 4}])

And want to apply a function on every value in every map and as a result I want the same vector of maps, something like this 并且想要对每个地图中的每个值应用一个函数,因此我想要相同的地图矢量,就像这样

(map #(+ 1 %) vector-of-maps)

So that the result is 这样的结果是

[{:a 2 :b 3} {:a 4 :b 5}]

And I want it to work with any vector of maps, not just this particular one.... 而且我希望它可以与任何地图矢量一起使用,而不仅仅是这个特定的地图...。

=> (defn update-map [m f] (reduce-kv (fn [m k v] (assoc m k (f v))) {} m))
=> (map #(update-map % inc) vector-of-maps)
({:b 3, :a 2} {:b 5, :a 4})

Perhaps 也许

(defn mapv-map-values [f vm]
  (letfn [(map-values [m] (zipmap (keys m) (map f (vals m))))]
    (mapv map-values vm)))

... producing ...生产

(mapv-map-values inc [{:a 1 :b 2} {:a 3 :b 4}])
;[{:b 3, :a 2} {:b 5, :a 4}]

The map-values function, the only significant departure from @user100464's answer , was adapted from here . map-values函数是@ user100464答案的唯一重大偏离,是从此处改编的。

also you can do like this,but it is ugly 你也可以这样做,但是很丑

(defn dodo [m] (map (fn [map] (apply merge (for [[k v] map] (assoc {} k (inc v))))) m))

(dodo [{:a 1 :b 2} {:a 3 :b 4}])
;({:a 2, :b 3} {:a 4, :b 5})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM