gpt4 book ai didi

clojure - 汇总(分组和计数)一系列 map

转载 作者:行者123 更新时间:2023-12-02 05:49:42 25 4
gpt4 key购买 nike

我试图在 Clojure 中找到一种惯用的方法,通过特定键对一系列映射进行分组并提供计数。有点像 SQL 中的“SELECT X, Y, COUNT(*) FROM Z GROUP BY X, Y”。数据如下所示:

({:status "Academy Sponsor Led",
:pupil-population "",
:locality "Northamptonshire",
:pupil-gender "Mixed",
:county "Northamptonshire",
:pupil-age "11-18",
:school "Wrenn School",
:website ""}
{:status "Academy Sponsor Led",
:pupil-population "915",
:locality "Plymouth",
:pupil-gender "Mixed",
:county "Devon",
:pupil-age "11-19",
:school "The All Saints Church of England Academy",
:website "http://www.asap.org.uk/"}
{:status "Academy Converter",
:pupil-population "735",
:locality "Somerset",
:pupil-gender "Mixed",
:county "Somerset",
:pupil-age "11-16",
:school "Stanchester Academy",
:website "www.Stanchester-Academy.co.uk"}
{:status "Community School",
:pupil-population "",
:locality "Herefordshire",
:pupil-gender "Mixed",
:county "Herefordshire",
:pupil-age "11-18",
:school "Lady Hawkins High School",
:website "http://www.lhs.hereford.sch.uk"}...

我的解决方案是这样的:

(defn summarise-locality-status
"Return counts of status within locality"
[data]
(let [locality (group-by :locality data)
locality-status (map #(vector (first %) (group-by :status (second %))) locality)
counts-fn (fn [locality-status-item]
(let [statuses (second locality-status-item)]
(map #(vector % (count (get statuses %))) (keys statuses))))]
(map #(vector (first %) (counts-fn %)) locality-status)))

但是感觉有点笨拙。这样做的更好方法是什么?

最佳答案

根据您的需要,

(frequencies (for [r data] (select-keys r [:locality :status])))

更接近 SQL,因为它没有嵌套。

关于clojure - 汇总(分组和计数)一系列 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24427152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com