clojure - Clojure:合并 2 个地图向量
问题描述
我有 2 个地图向量:employ-base 和employ1。我想合并employ1 的优先级高于employ-base 的2 个向量。因此,如果employ1 有记录使用它们,则使用来自employ-base 的记录。在clojure中最好的方法是什么?
从:
(def employ-base
[{:id 1 :name "Aaron" :income 0}
{:id 2 :name "Ben" :income 0}
{:id 3 :name "Carry" :income 0}])
(def employ1
[{:id 1 :name "Aaron" :income 1000}
{:id 3 :name "Carry" :income 2000}])
至:
(def employ1
[{:id 1 :name "Aaron" :income 1000}
{:id 2 :name "Ben" :income 0}
{:id 3 :name "Carry" :income 2000}])
解决方案
假设:id
每个员工都是唯一的,您可以对地图进行:id
分组,然后合并每个地图分组:id
:
(map
#(apply merge (val %))
(merge-with concat
(group-by :id employ-base)
(group-by :id employ1)))
=> ({:id 1, :name "Aaron", :income 1000}
{:id 2, :name "Ben", :income 0}
{:id 3, :name "Carry", :income 2000})
合并的优先级是通过合并employ1
after employe-base
、sincemerge
和merge-with
prefer 最右边的值来维护的。
推荐阅读
- excel - UDF - 如何将包含路径、工作簿名称、工作表名称和单元格引用的字符串转换为公式?
- reactjs - 根据先前的状态更改 Redux 中的状态
- jquery - Chart.render() 不是函数
- scrapy - 如何修复不同的元素文本以提取
- python - Pandas:从一系列数组创建新的数据框列
- vue.js - 第一次单击时提交状态为空白。Vuex
- bokeh - 如何根据给定的 x 值显示悬停信息?
- ruby-on-rails - 如何在会话结束前删除购物车和 LineItems?
- performance - 如何在golang中测量函数的执行时间,不包括等待时间
- java - 乘以投影矩阵后如何渲染三角形