我可以“转置”吗? Clojure 中的映射列表转换为列表映射?
你好,huys:我想为地图中的所有值绘制“平均值”。假设我有一个映射列表:
[{"age" 2 "height" 1 "weight" 10},
{"age" 4 "height" 4 "weight" 20},
{"age" 7 "height" 11 "weight" 40}]
我想要的输出是
{"age 5 "height" 5 ....}
///下面是我大脑的胡言乱语,即我想象它在 Clojure 中工作的方式...不要太认真地
转置列表:
{"age" [2 4 7] "height" [1 4 11] }
然后我可以简单地执行类似的操作(再次,在这里编写一个名为 freduce 的函数)
(freduce average (vals (map key-join list)))
来获取
{"age" 5 "weight" 10 "height" 7}
Hi huys : I want to map a "average" for all values in a map. say I have a list of maps :
[{"age" 2 "height" 1 "weight" 10},
{"age" 4 "height" 4 "weight" 20},
{"age" 7 "height" 11 "weight" 40}]
And my desired output is
{"age 5 "height" 5 ....}
///Below are the ramblings of my brain, i.e. the way I might imagine this working in Clojure...not to be taken too seriously
transpose the list :
{"age" [2 4 7] "height" [1 4 11] }
and then I could simply do something like (again, making up a function called freduce here)
(freduce average (vals (map key-join list)))
to get
{"age" 5 "weight" 10 "height" 7}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
创建向量图:
创建平均值图:
Create the map of vectors:
Create the map of averages:
看看 merge-with
这是我的一些实际代码:
Take a look at merge-with
Here's my go at some actual code:
这是一个相当详细的解决方案。希望有人能想出更好的办法:
Here's a fairly verbose solution. Hopefully someone can come up with something better:
演示
DEMO
这是另一个使用 merge-with 而不使用 zipmap 的版本。
Here's another version that uses merge-with without zipmap.
这是我的单行解决方案:
逻辑如下:
Here's my one-liner solution:
Logics as follows: