我想计算映射向量中场的累加和。发自:
(def data
[{:id 1 :name "John1" :income 5000}
{:id 2 :name "John2" :income 6000}
{:id 3 :name "John3" :income 7000}])
至:
(def data
[{:id 1 :name "John1" :income 5000}
{:id 2 :name "John2" :income 11000}
{:id 3 :name "John3" :income 18000}])
我有像(reductions + (map :income data))
这样的东西来做计算,但是如何形成新的向量呢?
发布于 2019-07-31 04:03:22
要继续您的解决方案(如果您不介意重复两次数据):
(map #(assoc %1 :income %2) data (reductions + (map :income data)))
; => ({:id 1, :income 5000, :name "John1"}
; => {:id 2, :income 11000, :name "John2"}
; => {:id 3, :income 18000, :name "John3"})
(或使用mapv
保留向量)
发布于 2019-07-31 02:34:25
> (reduce #(conj %1 (assoc %2 :income (+ (:income (last %1)) (:income %2)))) (vector (first data)) (rest data))
[{:id 1, :name "John1", :income 5000}
{:id 2, :name "John2", :income 11000}
{:id 3, :name "John3", :income 18000}]
发布于 2019-07-31 04:05:59
使用specter:
(transform (subselect ALL :income) #(reductions + %) data)
https://stackoverflow.com/questions/57277916
复制相似问题