在Clojure中将哈希映射内部翻出来

我是Clojure的新手,并为你的Clojure大师提出了一个有趣的问题.我正在编写“编程集体智能”一书,并尝试在Clojure中编写示例代码(本书将它们全部用Python编写).在第一章中,我们有一个电影评论家的哈希映射设置和他们给不同电影的排名.它看起来像这样:

{"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}}

问题是这个.如何将其内部转出,以便我得到一个如下所示的哈希映射:

{"Lady in the Water" {"Lisa Rose" 2.5, "Gene Seymour" 3.0},
 "Snakes on a Plane" {"Lisa Rose" 3.5, "Gene Seymour" 3.5}}

你有什么功能来实现这个目标?

最佳答案
(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中将哈希映射内部翻出来 - 代码日志