将映射M转换为映射数组A,其中来自M的键和值映射到A中元素中的新键

时间:2018-04-09 11:19:30

标签: clojure

给出这样的地图:

{
 "keystring1" "valuestring1"
 "keystring2" "valuestring2"
 ...
}

如何将其转换为这样的地图数组:

[
 {
  :newKey1 "keystring1"
  :newKey2 "valuestring1"
 }
 {
  :newKey1 "keystring2"
  :newKey2 "valuestring2"
 }
 ...
]

根据我的研究,我认为函数reduce-kvassoc在这里应该很有用,但我还是无法创建一个工作版本。

到目前为止,关闭的是:

 (reduce-kv (fn [m k v]
   (merge m (assoc {} :newkey1 k) (assoc {} :newkey2 v)))
   []
   {"keystring1" "valuestring1", "keystring2" "valuestring2"})

结果是:

[{:newkey1 "keystring1"} {:newkey2 "valuestring1"} {:newkey1 "keystring2"} {:newkey2 "valuestring2"}]

3 个答案:

答案 0 :(得分:3)

我喜欢使用for来做这样的事情。

(def m {"keystring1" "valuestring1"
        "keystring2" "valuestring2"})

> (for [[k v] m]
    {:newkey1 k
     :newkey2 v})

({:newkey1 "keystring1", :newkey2 "valuestring1"}
 {:newkey1 "keystring2", :newkey2 "valuestring2"})

如果真的需要,你可以强迫它成为一个矢量:

> (vec (for [[k v] m]
         {:newkey1 k
          :newkey2 v}))

[{:newkey1 "keystring1", :newkey2 "valuestring1"}
 {:newkey1 "keystring2", :newkey2 "valuestring2"}]

答案 1 :(得分:2)

以下是使用reduce-kv的解决方案:

(def my-map
  {"keystring1" "valuestring1"
   "keystring2" "valuestring2"})

(reduce-kv
  (fn [acc k v] (conj acc {:newKey1 k :newKey2 v}))
  []
  my-map)

或使用zipmap

(mapv #(zipmap [:newKey1 :newKey2] %) my-map)

两者都产生了这个:

=> [{:newKey1 "keystring1", :newKey2 "valuestring1"}
    {:newKey1 "keystring2", :newKey2 "valuestring2"}]

答案 2 :(得分:1)

还有一个,为了完整性:

from tkinter import* #

#creating instance of tkinter
obj = Tk()  
#Set title of our window form  
obj.title("MyFirst Window - WOW")
#Set dimension of form 
x_size = 1200
y_size = 600
obj.geometry(str(x_size)+"x"+str(y_size)) 

obj.update()

w = Canvas(obj, width=x_size, height=y_size)
w.place(x=0,y=obj.winfo_height()-100)
w.create_rectangle(0, 0, obj.winfo_width(), 100, fill="#476042")

def callback(event):
    print(str(obj.winfo_width())+'x'+str(obj.winfo_height()))
    w.config(width=obj.winfo_width(),height=obj.winfo_height())
    w.place(x=0,y=obj.winfo_height()-100)
    w.create_rectangle(0, 0, obj.winfo_width(), 100, fill="#476042")

window = obj
window.bind("<Configure>", callback)

obj.mainloop()

user> (map (partial zipmap [:new-key1 :new-key2]) data)

;;=> ({:new-key1 "keystring1", :new-key2 "valuestring1"} 
;;    {:new-key1 "keystring2", :new-key2 "valuestring2"})