Clojure:对映射集合中的值求和
我试图通过地图的公共键来总结地图集合的值。我有这个片段:
(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”,但它仅适用于序列,不适用于集合。
谢谢。
===编辑====
使用 Joost 的建议,我得出了这样的结论:
(apply merge-with + (for [x data] (select-keys x [:col0 :col1 :col2]))
这会迭代一个集合并对所选键求和。我添加的“选择键”部分是特别需要的,以避免当集合中的地图包含文字而不仅仅是数字时遇到麻烦。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您确实想对公共键的值求和,您可以一步完成整个转换:
对您拥有的子序列求和:
If you really want to sum the values of the common keys you can do the whole transformation in one step:
To sum the sub sequences you have: