Clojure getting highest value from zipmap

孤街浪徒 提交于 2021-01-24 07:34:51

问题


So I've got my proposed zip map here and it works perfectly. As you can see I've got the data loading.

That is what it looks like in the repl which is perfect. And right here is the map

:Year 2020, :Day 27, :January 59, :February 38
:Year 2020, :Day 28, :January 41, :February 57
:Year 2020, :Day 29, :January 56, :February 51
:Year 2020, :Day 31, :January 94, :February -999
:Year 2020, :Day 30, :January 76, :February -999 

(map [:Day :Month

Bear in mind this is just a snippet of the code I've done. How would you propose I find the highest value day in January? And by highest I mean by the number next to the months

(into(sorted-map-by >(fn [:January]))Ha) 

I tried this to no success, The "Ha" at the end is just the name of the function where I am initialising the zipmap and using io/reader to read the file


回答1:


I would use max-key and reduce:

(def data [{:Year 2020, :Day 27, :January 59, :February 38}
           {:Year 2020, :Day 28, :January 41, :February 57}
           {:Year 2020, :Day 29, :January 56, :February 51}
           {:Year 2020, :Day 31, :January 94, :February -999}
           {:Year 2020, :Day 30, :January 76, :February -999}])

(reduce (partial max-key :January) data)
;; => {:Year 2020, :Day 31, :January 94, :February -999}

(:Day (reduce (partial max-key :January) data))
;; => 31



回答2:


Not sure how your exact datastructure looks like, but assuming it's a vector of maps you can do something like this:

(def data
  [{:Year 2020, :Day 27, :January 59, :February 38}
   {:Year 2020, :Day 28, :January 41, :February 57}
   {:Year 2020, :Day 29, :January 56, :February 51}
   {:Year 2020, :Day 31, :January 94, :February -999}
   {:Year 2020, :Day 30, :January 76, :February -999}])

(->> data
     (sort-by :January)
     last
     :January)
;; => 94

Sorting the vector by using a keyword as a function to look up its value in the map, then taking the vector with the highest value for January, then get the value belonging to the key :January from that vector. Let me know if your data structure looks a bit different.




回答3:


@Rulle's answer is very good. Without max-key it would be:

(def data [{:Year 2020, :Day 27, :January 59, :February 38}
           {:Year 2020, :Day 28, :January 41, :February 57}
           {:Year 2020, :Day 29, :January 56, :February 51}
           {:Year 2020, :Day 31, :January 94, :February -999}
           {:Year 2020, :Day 30, :January 76, :February -999}])

(defn seq-max [seq greater key]
  (reduce (fn [a b] (if (greater (key a) (key b)) a b)) seq))
;; if no key is wanted, choose the function `identity` as key!
;; e.g.
;; (seq-max (map :January data) > identity)
;; => 94

(:Day (seq-max data > :January)) ;; => 31


来源:https://stackoverflow.com/questions/65725987/clojure-getting-highest-value-from-zipmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!