从向量获取字符串值



我有这个字符串向量:

["Color: Black" "Color: Blue" "Size: S" "Size: XS"]

如何获取colorSize的所有值?

例如,输出应为 ["color" ["Black" "Blue"]]

此解决方案按属性名称(颜色、大小等)拆分每个字符串和组,然后清理预期值:

    user=> (require '[clojure.string :as string])
    nil
    user=> (def attributes ["Color: Black" "Color: Blue" "Size: S" "Size: XS"])
    #'user/attributes
    user=> (as-> attributes x
      #_=>   (map #(string/split % #": ") x)
      #_=>   (group-by first x)
      #_=>   (reduce-kv #(assoc %1 %2 (mapv second %3)) {} x))
    {"Color" ["Black" "Blue"], "Size" ["S" "XS"]}

我宁愿用reduce一次性完成(因为它更短,可能更快):

user> (require '[clojure.string :as cs])
nil
user> (def data ["Color: Black" "Color: Blue" "Size: S" "Size: XS"])
#'user/data
user> (reduce #(let [[k v] (cs/split %2 #": ")]
                 (update %1 k (fnil conj []) v))
              {} data)
{"Color" ["Black" "Blue"], "Size" ["S" "XS"]}

最新更新