我有两个地图阵列
第一是 [{:a 1 :b 2 :d 6} {:a 2 :b 2} {:a 7 :b 7}]
第二是 [{:a 3 :c 3 :e 9 :y 7} {:a 2 :b 6 :c 8}]
取决于它的值,a即如果它在第二个数组中匹配,那么'第二个地图'应该与'第一个地图'合并,并且得到的地图数组应该是
Res应该是 [{:a 1 :b 2 :d 6} {:a 2 :b 6 :c 8} {:a 7 :b 7} {:a 3 :c 3 :e 9 :y 7}]
谁可以帮我这个事.提前致谢.
干得好:
user> (def xs [{:a 1 :b 2 :d 6} {:a 2 :b 2} {:a 7 :b 7}])
#'user/xs
user> (def ys [{:a 3 :c 3 :e 9 :y 7} {:a 2 :b 6 :c 8}])
#'user/ys
user> (for [[a ms] (group-by :a (concat xs ys))] (apply merge ms))
({:a 1, :b 2, :d 6} {:a 2, :c 8, :b 6} {:a 7, :b 7} {:y 7, :a 3, :c 3, :e 9})
Run Code Online (Sandbox Code Playgroud)
这个数据结构对我来说看起来非常笨拙,但我的看法是:
(defn key-by-a [coll]
"Convert a list of maps to a map of maps keyed by their vals at :a"
(apply hash-map (mapcat (juxt :a identity) coll)))
(defn merge-map-lists [l1 l2]
(->> [l1 l2]
(map key-by-a)
(apply merge-with merge)
(vals)))
Run Code Online (Sandbox Code Playgroud)
它不做的一件事是维护输入列表的顺序,但由于不清楚哪个列表决定(两者可能具有不同顺序的相同键),所以我将其排除在外。
| 归档时间: |
|
| 查看次数: |
1497 次 |
| 最近记录: |