在Clojure中打开哈希映射 [英] Turn a hash map inside out in Clojure
问题描述
我是Clojure的新手,对你有一个有趣的问题Clojure大师。我正在编写编程集体智慧一书,并试图在Clojure中编写示例(本书在Python中都有它们)。在第一章中,我们有一个哈希映射设置的电影评论家和他们给不同的电影排名。它看起来像这样:
{Lisa Rose{水之女人2.5,Snakes on a Plane3.5 },
Gene Seymour{女人在水中3.0,蛇在飞机上3.5}}
问题是这样的。如何将内部翻转,使我得到一个哈希映射,看起来像这样:
{Lady in the Water{ Lisa Rose2.5,Gene Seymour3.0},
pre>
Snakes on a Plane{Lisa Rose3.5,Gene Seymour3.5}}
您的功能是什么?
解决方案$ p>
(let [m {Lisa Rose{水之女人2.5,蛇在飞机上3.5},
Gene Seymour{ 3.0,Snakes on a Plane3.5}}]
(apply merge-with merge
(for [[ok ov] m
[ik iv] ov]
{ {Gene Seymour3.5,Lisa Rose3.5},
女人在水中{ Gene Seymour3.0,Lisa Rose2.5}}
I am very new to Clojure and have an interesting problem for you Clojure gurus. I'm working through the book "Programming Collective Intelligence" and trying to code the examples in Clojure (the book has them all in Python). In the first chapter we have a hash map setup of movie critics and the rankings they've given to different movies. It looks like this:
{"Lisa Rose" {"Lady in the Water" 2.5, "Snakes on a Plane" 3.5 },
"Gene Seymour" {"Lady in the Water" 3.0, "Snakes on a Plane" 3.5}}
The problem is this. How to turn that inside out so that I get a hash map that looks like this:
{"Lady in the Water" {"Lisa Rose" 2.5, "Gene Seymour" 3.0},
"Snakes on a Plane" {"Lisa Rose" 3.5, "Gene Seymour" 3.5}}
What would be your function to accomplish this?
(let [m {"Lisa Rose" {"Lady in the Water" 2.5, "Snakes on a Plane" 3.5 },
"Gene Seymour" {"Lady in the Water" 3.0, "Snakes on a Plane" 3.5}}]
(apply merge-with merge
(for [[ok ov] m
[ik iv] ov]
{ik {ok iv}})))
{"Snakes on a Plane" {"Gene Seymour" 3.5, "Lisa Rose" 3.5},
"Lady in the Water" {"Gene Seymour" 3.0, "Lisa Rose" 2.5}}
这篇关于在Clojure中打开哈希映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!