Clojure地图嵌套

时间:2014-01-16 11:15:02

标签: clojure

我有这样的矢量结构......

[{:email "email@gmail.com", :password "pass"} 
 {:email "email2@yahoo.com", :password "pass2"} 
 {:email "email3@yahoo.com", :password "pass3"} 
 {:email "email4@gmail.com", :password "pass4"}]

我怎样才能制作出这样的地图?两个电子邮件值必须相同......

 {{"email@gmail.com"{:email "email@gmail.com", :password "pass"}}, 
  {"email2@yahoo.com"{:email "email2@yahoo.com", :password "pass2"}}, 
  {"email3@yahoo.com" {:email "email3@yahoo.com", :password "pass3"}} ,
  {"email4@gmail.com"{:email "email4@gmail.com", :password "pass4"}}     

我对clojure有点新意,所以感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

(def a [{:email "email@gmail.com", :password "pass"}
        {:email "email2@yahoo.com", :password "pass2"}
        {:email "email3@yahoo.com", :password "pass3"}
        {:email "email4@gmail.com", :password "pass4"}])

(zipmap (map :email a) a)

创建一系列电子邮件地址,然后将原始地图的矢量拉伸到新地图中,地址为关键字,原始地图为值。

(想想左边垂直显示的电子邮件列表,右边是垂直显示的原始地图条目,还有一个拉链向下移动,将它们连接在一起)

答案 1 :(得分:0)

另一种选择(虽然你的输出将嵌套在一个向量中)是使用group-by

user=> (def a [{:email "email@gmail.com", :password "pass"}
        {:email "email2@yahoo.com", :password "pass2"}
        {:email "email3@yahoo.com", :password "pass3"}
        {:email "email4@gmail.com", :password "pass4"}])
#'user/a
user=> (group-by :email a)
{"email@gmail.com" [{:email "email@gmail.com", :password "pass"}], "email2@yahoo.com" [{:email "email2@yahoo.com", :password "pass2"}], "email3@yahoo.com" [{:email "email3@yahoo.com", :password "pass3"}], "email4@gmail.com" [{:email "email4@gmail.com", :password "pass4"}]}
user=>