向向量中的向量序列添加键并将其转换为哈希映射

时间:2017-11-28 19:26:57

标签: clojure lisp

鉴于

[["foo" "bar" 2] ["biz" "baf" 3]] 

我如何获得

[{:a "foo" :b "bar" :num 2} {:a "biz" :b "baf" :num 3}]?

实际上,我的向量有数百个向量需要添加键并转换为哈希映射。

2 个答案:

答案 0 :(得分:1)

莱特温斯基说了什么,或者:

(def input [["foo" "bar" 2]["biz" "baf" 3]])

(mapv (fn [[a b num]]
        {:a a
         :b b
         :num num}) input)

如果您需要转换大量数据,可能mapv不是最佳选择,因为它会将整个向量同时保留在内存中。在这种情况下,正常map会创建一个懒惰的seq或换能器可能会更好。

答案 1 :(得分:0)

一般解决方案:

(defn vectors->maps 
 "takes a vector of vectors containing values and a vector of keys
  and returns a vector of maps such that each value at index n in the value 
  vector is paired with each key at index n in the keys vector
  ex: (vectors->maps [["foo" "bar" 2] ["biz" "baf" 3]], [:a :b :num]) 
         => [{:a "foo", :b "bar", :num 2} {:a "biz", :b "baf", :num 3}]"
  [vectors keys] 
 (mapv (partial zipmap keys) vectors))

为读者练习:为此函数编写规范并为其生成测试以找出任何边缘情况