合并地图而不覆盖键 [英] Merging maps without overriding keys
本文介绍了合并地图而不覆盖键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个clojure函数,它返回一键映射序列。我想将这些地图合并为一张地图;但是,如果有些地图具有相同的键,则我不想覆盖这些值,而只是将它们组合成一个向量。 合并
似乎会覆盖,而与
合并似乎会严重扭曲类型。
I have a clojure function that returns a sequence of 1-key maps. I want to merge these maps into one map; however, if there are maps with the same key, I don't want to overwrite the values, only to combine them into a vector. merge
seems to overwrite, and merge-with
seems to seriously distort the type.
我有:
({:foo "hello"}
{:bar "world"}
{:baz "!!!"}
{:ball {:a "abc", :b "123"}}
{:ball {:a "def", :b "456"}}
{:ball {:a "ghi", :b "789"}})
我想要:
{:foo "hello"
:bar "world"
:baz "!!!"
:ball [{:a "abc", :b "123"} {:a "def", :b "456"} {:a "ghi", :b "789"}]}
谢谢。
推荐答案
(def data ...) ;; your list of maps
(apply merge-with (comp flatten vector) data)
;; => {:baz "!!!", :ball ({:b "123", :a "abc"} {:b "456", :a "def"} {:b "789", :a "ghi"}), :bar "world", :foo "hello"}
注意:在OP的情况下,可以使用 flatten
,但不是在创建属于冲突键的值向量时合并地图的一般方法。
Note: the use of flatten
works in OP's case but is NOT a general way to merge maps while creating vectors of values belonging to colliding keys.
这篇关于合并地图而不覆盖键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文