在 Clojure 中将字符串向量转换为哈希映射
Convert vector of strings into hash-map in Clojure
我有以下数据结构:
["a 1" "b 2" "c 3"]
如何将其转换为哈希映射?
我想要以下数据结构:
{:a 1 :b 2 :c 3}
使用clojure.string/split
and then use keyword
和Integer/parseInt
:
(->> ["a 1" "b 2" "c 3"]
(map #(clojure.string/split % #" "))
(map (fn [[k v]] [(keyword k) (Integer/parseInt v)]))
(into {}))
=> {:a 1, :b 2, :c 3}
(into {}
(map #(clojure.edn/read-string (str "[:" % "]")))
["a 1" "b 2" "c 3"])
;; => {:a 1, :b 2, :c 3}
还有一个:)
(->> ["a 1" "b 2" "c 3"]
(clojure.pprint/cl-format nil "{~{:~a ~}}")
clojure.edn/read-string)
;;=> {:a 1, :b 2, :c 3}
(def x ["a 1" "b 2" "c 3"])
(clojure.edn/read-string (str "{:" (clojure.string/join " :" x) "}"))
;;=> {:a 1, :b 2, :c 3}
我有以下数据结构:
["a 1" "b 2" "c 3"]
如何将其转换为哈希映射?
我想要以下数据结构:
{:a 1 :b 2 :c 3}
使用clojure.string/split
and then use keyword
和Integer/parseInt
:
(->> ["a 1" "b 2" "c 3"]
(map #(clojure.string/split % #" "))
(map (fn [[k v]] [(keyword k) (Integer/parseInt v)]))
(into {}))
=> {:a 1, :b 2, :c 3}
(into {}
(map #(clojure.edn/read-string (str "[:" % "]")))
["a 1" "b 2" "c 3"])
;; => {:a 1, :b 2, :c 3}
还有一个:)
(->> ["a 1" "b 2" "c 3"]
(clojure.pprint/cl-format nil "{~{:~a ~}}")
clojure.edn/read-string)
;;=> {:a 1, :b 2, :c 3}
(def x ["a 1" "b 2" "c 3"])
(clojure.edn/read-string (str "{:" (clojure.string/join " :" x) "}"))
;;=> {:a 1, :b 2, :c 3}