Clojure:对地图集合中的值求和 [英] Clojure: summing values in a collection of maps
问题描述
我试图通过它们的公共密钥对地图集合的值进行求和。我有这个代码片段:
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)
基本上,
我现在的问题是如何总结这些值?我试图使用reduce但是
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.
感谢。
=== EDIT ====
===EDIT====
使用Joost的建议我出来了:
Using the suggestion from Joost I came out with this:
(apply merge-with + (for [x data] (select-keys x [:col0 :col1 :col2]))
b $ b
这会迭代一个集合并对选择的键求和。我添加的select-keys部分是特别需要避免的麻烦,当集合中的地图包含文字,而不仅仅是数字。 p>
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.
推荐答案
如果你真的想对通用键的值求和,可以一步完成整个转换:
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}
(apply map + '((1 2) (1 2)))
=> (2 4)
这篇关于Clojure:对地图集合中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!