我想计算地图矢量中一个字段的累积和。发件人:
(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))
的东西来进行计算,但是如何形成新矢量?
答案 0 :(得分:3)
要继续您的解决方案(并且如果您不介意重复数据两次):
(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
保持向量)
答案 1 :(得分:2)
> (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}]
答案 2 :(得分:1)
使用幽灵:
(transform (subselect ALL :income) #(reductions + %) data)