Clojure:对映射集合中的值求和

发布于 2024-12-12 09:22:41 字数 521 浏览 0 评论 0原文

我试图通过地图的公共键来总结地图集合的值。我有这个片段:

(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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萝莉病 2024-12-19 09:22:41

如果您确实想对公共键的值求和,您可以一步完成整个转换:

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

对您拥有的子序列求和:

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

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文