在Clojure中按多个键分组

时间:2012-02-01 00:39:46

标签: clojure

如何按多个键对地图集合进行分组?

例如:

(def m1 [{:a 1 :b 2 :c 3}
         {:a 1 :b 2 :c 4}
         {:a 1 :b 4 :c 3}
         {:a 1 :b 4 :c 3}])

(group-by-x [:a :b] m1)

我想回复一下:

[{:a 1 :b 2} [{:a 1 :b 2 :c 3}{:a 1 :b 2 :c 4}],
 {:a 1 :b 4} [{:a 1 :b 4 :c 3}{:a 1 :b 4 :c 3}]]

1 个答案:

答案 0 :(得分:22)

(group-by #(select-keys % [:a :b]) m1)

这会返回一张地图:

{{:b 2, :a 1} [{:a 1, :c 3, :b 2} {:a 1, :c 4, :b 2}],
 {:b 4, :a 1} [{:a 1, :c 3, :b 4} {:a 1, :c 3, :b 4}]}

要准确获取您指定的返回值,请将其包装在(vec (apply concat ...))

(vec (apply concat (group-by #(select-keys % [:a :b]) m1)))
; => as in the question text

这是等效的,但可能更漂亮:

(->> (group-by #(select-keys % [:a :b]) m1)
     (apply concat)
     vec)