在 clojure 中按键值降序对地图列表进行排序

sort a list of maps by value of a key in descending order in clojure

我有一个目录大小为字符串的地图列表。我想按大小降序排序: 问题是它也包含单位,即 GB 或 MB

列表看起来像这样:

    ({:directory_path /user/dod/1, :directory_size 8.49 MB} {:directory_path /user/dod/22, :directory_size 1.66 GB} {:directory_path /user/dod/testorc, :directory_size 1.28 MB} )

是否需要按大小降序对它进行排序?

你可以这样做:

(defn str->float [s]
  (Float. s))

(defn filesize->num [fs]
  (let [[size unit] (clojure.string/split fs #" ")
        size (str->float size)]
    (condp = unit
          "MB" size
          "GB" (* size 1000))))

(def ->ds #(-> % :directory_size filesize->num))

(defn sort-data [data]
  (sort-by ->ds #(compare %2 %1) data))

(def data [{:directory_path "/user/dod/2", :directory_size "8.49 MB"}
           {:directory_path "/user/dod/22", :directory_size "1.66 GB"}
           {:directory_path "/user/dod/testorc", :directory_size "1.28 MB"}])

(sort-data data)