我有这个字符串向量:
["Color: Black"
"Color: Blue"
"Size: S"
"Size: XS"]
如何获取color
和Size
的所有值?
例如,输出应该是
["color" ["Black" "Blue"]]
答案 0 :(得分:4)
此解决方案按属性名称(颜色,大小等)拆分每个字符串,组,然后清除预期值:
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"]}
答案 1 :(得分:3)
我宁愿一次性使用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"]}