[英]Map of vectors to vector of maps
I would like to replace this structure, 我想替换这个结构,
{:a [1 2 .. 3] :b [1 2 .. 3] :c [1 2 3 ..]}
to this. 为此。
[{:a 1 :b 1 c 1} {:a 2 :b 2 :c 2} {:a 3 :b 3 :c 3} ...]
Number of keys is not specified. 未指定键数。
I found the solution, very ugly solution, but it can explain what I need. 我找到了解决方案,非常丑陋的解决方案,但是它可以解释我的需求。
#(map (fn [line]
(zipmap (keys %) line))
(partition (count (keys %))
(apply interleave (vals %))))
If anyone could simplify this, it would be great. 如果有人能简化这一点,那就太好了。
EDIT: 编辑:
#(map (fn [vs]
(zipmap (keys %) vs))(apply map vector (vals %)))
(def z (sorted-map :a [1 2 3 4] :b ["a" "b" "c" "d"] :c [:i :j :k :l]))
(defn x []
(let [k (repeat (keys z))
v (apply map vector (vals z))]
(map zipmap k v)))
user> (x)
({:c :i, :b "a", :a 1} {:c :j, :b "b", :a 2} {:c :k, :b "c", :a 3} {:c :l, :b "d", :a 4})
Here is another solution 这是另一种解决方案
#(mapv
(partial apply merge)
(map val
(group-by (comp second first)
(for [[x y] % z y] (hash-map x z)))))
;=>[{:a 1, :c 1, :b 1} {:a 2, :c 2, :b 2} {:a 3, :c 3, :b 3}]
(let [x {1 [:a :b :c], 2 [:d :e :f], 3 [:g :h :i]}
k (vec (keys x))
r (map #(apply merge %)
(apply map (fn [ & a]
(merge (map-indexed
(fn [idx v] {(k idx) v}) a))) (vals x)))]
(println r))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.