如何根据动态给出的列值对嵌套集合进行分组?例如,假设我们有以下嵌套集合;如何按第一列和第二列中的值将其分组?
[ ["A" 2011 "Dan"] ["A" 2011 "Jon"] ["A" 2010 "Tim"] ["B" 2009 "Tom"] ]
所需的结果图为:

{ A {
      2011 [['A', 2011, 'Dan'] ['A', 2011, 'Joe']]
      2010 [['A', 2010, 'Tim']]
    }
  B { 2009 [['B', 2009, 'Tom']] }
}

以下是我的解决方案,几乎可以解决:
(defn nest [data criteria]
  (if (empty? criteria)
    data
    (for [[k v] (group-by #(nth % (-> criteria vals first)) data)]
      (hash-map k (nest v (rest criteria))))))

最佳答案

我想出了以下几点:

user=> (def a [["A" 2011 "Dan"]
               ["A" 2011 "Jon"]
               ["A" 2010 "Tim"]
               ["B" 2009 "Tom"] ])

user=> (into {} (for [[k v] (group-by first a)]
                  [k (group-by second v)]))

{"A" {2011 [["A" 2011 "Dan"]
            ["A" 2011 "Jon"]],
      2010 [["A" 2010 "Tim"]]},
 "B" {2009 [["B" 2009 "Tom"]]}}

关于clojure - 如何根据给定的标准对嵌套集合进行分组?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7668695/

10-10 01:16