在 Clojure 中,如何对元素进行分组?
在 clojure 中,我想聚合这些数据:
(def data [[:morning :pear][:morning :mango][:evening :mango][:evening :pear]])
(group-by first data)
;{:morning [[:morning :pear][:morning :mango]],:evening [[:evening :mango][:evening :pear]]}
我的问题是 :evening
和 :morning
是多余的。 相反,我想创建以下集合:
([:morning (:pear :mango)] [:evening (:mango :pear)])
我想出了:
(for [[moment moment-fruit-vec] (group-by first data)] [moment (map second moment-fruit-vec)])
是否有更惯用解决方案?
In clojure, I want to aggregate this data:
(def data [[:morning :pear][:morning :mango][:evening :mango][:evening :pear]])
(group-by first data)
;{:morning [[:morning :pear][:morning :mango]],:evening [[:evening :mango][:evening :pear]]}
My problem is that :evening
and :morning
are redundant.
Instead, I would like to create the following collection:
([:morning (:pear :mango)] [:evening (:mango :pear)])
I came up with:
(for [[moment moment-fruit-vec] (group-by first data)] [moment (map second moment-fruit-vec)])
Is there a more idiomatic solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我也遇到过类似的分组问题。通常我最终会将 merge-with 或 update-in 插入到某个 seq 处理步骤中:
您会得到一个映射,但这只是一个键值对的 seq:
但是,如果每个键出现两次,此解决方案只能得到您想要的内容。这可能会更好:
这两者都感觉“更实用”,但也感觉有点复杂。不要太快地否定您的解决方案,它很容易理解并且功能足够。
I've come across similar grouping problems. Usually I end up plugging merge-with or update-in into some seq processing step:
You get a map, but this is just a seq of key-value pairs:
This solution only gets what you want if each key appears twice, however. This might be better:
Both of these feel "more functional" but also feel a little convoluted. Don't be too quick to dismiss your solution, it's easy-to-understand and functional enough.
不要太快地关闭
group-by
,它已按所需的键聚合您的数据,并且它没有更改数据。任何其他需要矩-果对序列的函数都将接受在group-by
返回的映射中查找的任何值。在计算摘要方面,我倾向于使用
merge-with
,但为此我必须将输入数据转换为一系列映射,并使用所需的键和构造一个“基本映射”空向量作为值。Don't be too quick to dismiss
group-by
, it has aggregated your data by the desired key and it hasn't changed the data. Any other function expecting a sequence of moment-fruit pairs will accept any value looked up in the map returned bygroup-by
.In terms of computing the summary my inclination was to reach for
merge-with
but for that I had to transform the input data into a sequence of maps and construct a "base-map" with the required keys and empty-vectors as values.思考 @mike t 的答案,我想出了:
当按键出现时,此解决方案也有效
data
上的次数超过两次:Meditating on @mike t's answer, I've come up with:
This solution works also when the keys appear more than twice on
data
:也许只需稍微修改一下标准分组:
然后将其用作:
maybe just modify the standard group-by a little bit:
then use it as: