矢量的地图从列表

时间:2018-02-12 22:05:28

标签: clojure clojurescript

我如何获得以下内容:

[{:foo "a" :bar "b" :biz "c"}
 {:foo "d" :bar "e" :biz "f"}
 {:foo "h" :bar "i" :biz "j"}]

("a" "d" "h")
("b" "e" "i")
("c" "f" "j")

提前致谢!

3 个答案:

答案 0 :(得分:4)

您可以使用mapzipmap转置输入来创建结果地图:

(def input ['("a" "d" "h")
            '("b" "e" "i")
            '("c" "f" "j")])

(mapv #(zipmap [:foo :bar :biz] %) (apply map vector input))

答案 1 :(得分:2)

这与@ lee的变体非常相似,但它是一次性使用,使用clojure map能够对多个集合进行操作:

(def input ['("a" "d" "h")
            '("b" "e" "i")
            '("c" "f" "j")])

(apply mapv #(zipmap [:foo :bar :biz] %&) input)
;;=> [{:foo "a", :bar "b", :biz "c"} 
;;    {:foo "d", :bar "e", :biz "f"} 
;;    {:foo "h", :bar "i", :biz "j"}]

答案 2 :(得分:0)

map可以对多个序列进行操作。当给出多个序列时,它将从每个序列中获取元素并使用它们调用您的函数:

(let [s1 '("a" "d" "h")
      s2 '("b" "e" "i")
      s3 '("c" "f" "j")]
  (map (fn [x y z]
         {:foo x :bar y :baz z})
       s1 s2 s3))
;; =>
({:foo "a", :bar "b", :baz "c"}
 {:foo "d", :bar "e", :baz "f"}
 {:foo "h", :bar "i", :baz "j"})