Clojure: summing values in a collection of maps

大兔子大兔子 提交于 2020-01-11 09:18:12

问题


I am trying to sum up values of a collection of maps by their common keys. I have this snippet:

(def data [{:a 1 :b 2 :c 3} {:a 1 :b 2 :c 3}]
(for [xs data] (map xs [:a :b]))
((1 2) (1 2))

Final result should be ==> (2 4)

Basically, I have a list of maps. Then I perform a list of comprehension to take only the keys I need.

My question now is how can I now sum up those values? I tried to use "reduce" but it works only over sequences, not over collections.

Thanks.

===EDIT====

Using the suggestion from Joost I came out with this:

(apply merge-with + (for [x data] (select-keys x [:col0 :col1 :col2]))

This iterates a collection and sums on the chosen keys. The "select-keys" part I added is needed especially to avoid to get in trouble when the maps in the collection contain literals and not only numbers.


回答1:


If you really want to sum the values of the common keys you can do the whole transformation in one step:

(apply merge-with + data)
=> {:a 2, :b 4, :c 6}

To sum the sub sequences you have:

(apply map + '((1 2) (1 2)))
=> (2 4)


来源:https://stackoverflow.com/questions/7927899/clojure-summing-values-in-a-collection-of-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!