简体   繁体   中英

Convert a list of maps by the values of the maps [clojure]

I have a list filled with many maps (all of them have the same key), like this:

({:a 1} {:a 1} {:a 2} {:a 2} {:a 3} {:a 2})

I would like to convert it to a map that stores the occurrence of the value of each map. For exemple, the list above should return the following map:

{:1 2, :2 3, :3 1}

Any ideas on how can i do that?

(def m '({:a 1} {:a 1} {:a 2} {:a 2} {:a 3} {:a 2}))

(frequencies (map :a m)) ;; => {1 2, 2 3, 3 1}

Note the keys of the result are not keywords, as that would be an odd thing to do.

I would solve it like this:

(ns tst.demo.core
  (:use demo.core tupelo.core tupelo.test))

(defn maps->freqs
  [maps]
  (frequencies
    (for [m maps]
      (second (first m)))))

(dotest
  (let [data (quote
               ({:a 1} {:a 1} {:a 2} {:a 2} {:a 3} {:a 2}))]
    (is= (maps->freqs data)
      {1 2, 2 3, 3 1})))

The above uses my favorite template project. The best technique is to build it up slowely:

(defn maps->freqs
  [maps]
  (for [m maps]
    (first m)))

then (spyx-pretty (maps->freqs data)) produces

(maps->freqs data) => 
[[:a 1] [:a 1] [:a 2] [:a 2] [:a 3] [:a 2]]

modify it:

(defn maps->freqs
  [maps]
  (for [m maps]
    (second (first m))))

with result

(maps->freqs data) => 
[1 1 2 2 3 2]

Then use frequencies to get the final result.

Please be sure to read the list of documentation , especially the Clojure CheatSheet!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM