[英]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.我想将其转换为存储每个 map 值出现的 map。 For exemple, the list above should return the following map:例如,上面的列表应返回以下 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然后(spyx-pretty (maps->freqs data))
产生
(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.然后使用frequencies
得到最终结果。
Please be sure to read the list of documentation , especially the Clojure CheatSheet!请务必阅读文档列表,尤其是 Clojure CheatSheet!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.