[英]Convert map of list into list of maps (i.e. rows to colums)
I have the following data structure in Clojure 我在Clojure中具有以下数据结构
{:a [1 2 3]
:b [4 5 6]
:c [7 8 9]}
And I'd like to convert it into something like 我想将其转换为
[{:a 1 :b 4 :c 7}
{:a 2 :b 5 :c 8}
{:a 3 :b 6 :c 9}]
At the moment I'm kinda stumped as to how to do this. 此刻,我对如何做到这一点有些困惑。
In Clojure you can never guarantee the order of keys in maps after transformations. 在Clojure中,您永远无法保证变换后键在地图中的顺序。 They're indexed by key, not by order.
它们是通过键而不是顺序来索引的。
Vectors are, however. 向量是。 And with
get-in
you can do a lookup on position with a vector of coordinates . 借助
get-in
您可以使用坐标向量在位置上进行查找。
=> (def mat
[[1 2 3]
[4 5 6]
[7 8 9]])
=> (defn transpose
[m]
(apply mapv vector m))
=> (get-in (transpose mat) [1 2])
8
Got it: 得到它了:
(defn transpose-lists [x]
(map (fn [m] (zipmap (keys x) m)) (apply map vector (vals x))))
Unfortunately it doesn't preserve order of the keys. 不幸的是,它不保留键的顺序。 If anyone has a better solution then of course I'd like to hear it!
如果有人有更好的解决方案,那么我当然想听听!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.