计算clojure中的分组数据

时间:2013-08-13 18:06:26

标签: clojure

我在clojure中有数据,我按应用程序将其分组为以下格式:

(["name1" [{:application "name1", :date "date1", :description "desc1"}
           {:application "name1", :date "date2", :description "desc2"}]]
 ["name2" [{:application "name2", :date "date1", :description "desc1"}
           {:application "name2", :date "date2", :description "desc2"}]]
 ...  and so on)

我需要计算每个应用程序的事件数(即每个向量中的映射数),并生成以下格式的映射列表:

 ({:application "name1", :count 2} {:application "name2", :count2} ... etc )

我有以下代码来生成应用程序名称列表和每个应用程序名称的计数列表,但我正在努力解决如何将它们恢复为上述格式。

 (let[
  application-list (map first group-by-app)
  grouped-data (map second group-by-app)
  count-list (map count grouped-data)]

非常感谢任何帮助。

提前致谢。 大卫

3 个答案:

答案 0 :(得分:1)

for提供了一种非常简洁但富有表现力的方法,可以使用序列元素来构建新序列。我肯定会在这里推荐它。

(def group-by-app '(["name1" [{:application "name1", :date "date1", :description "desc1"}
                            {:application "name1", :date "date2", :description "desc2"}]]
                  ["name2" [{:application "name2", :date "date1", :description "desc1"}
                            {:application "name2", :date "date2", :description "desc2"}]]))

(for [[application events] group-by-app]
     {:application application, :count (count events)})

; => ({:application "name1", :count 2} {:application "name2", :count 2})

但是,为了完整起见,值得注意的是map可以同时在多个序列上映射函数。因此,您可以使用应用程序的功能和计数重新组合您生成的中间数据。

(let [application-list (map first group-by-app)
      grouped-data (map second group-by-app)
      count-list (map count grouped-data)]
  (map
    (fn [app event-count]
        {:application app :count event-count})
    application-list count-list))

答案 1 :(得分:1)

group-by生成一个映射,它是一系列键值对。您可以简单地映射该序列。

user=> (def foo #{{:application "name1", :date "date1", :description "desc1"}
  #_=>            {:application "name1", :date "date2", :description "desc2"}
  #_=>            {:application "name2", :date "date1", :description "desc1"}
  #_=>            {:application "name2", :date "date2", :description "desc2"}})
#'user/foo
user=> (map #(let [[key tuples] %] [key (count tuples)]) (group-by :application foo))
(["name1" 2] ["name2" 2])

如果您需要,可以将其转回地图。

user=> (into {} (map #(let [[key tuples] %] [key (count tuples)]) (group-by :application foo)))
{"name1" 2, "name2" 2}

答案 2 :(得分:0)

(reduce
  (fn [acc [_ maps]]
    (let [c (count maps)]
      (into acc 
        (map #(assoc % :count c) maps))))
  '()
  grouped)

分组是您提供的分组数据。