You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Clojure中将字符串向量转换为指定结构的hash-map

Clojure 字符串数组转哈希映射方案

核心转换逻辑:

  • 遍历数组中的每个字符串,按空格切割为键名、值两部分
  • 将字符串键名转换为Clojure关键字,将值字符串转换为对应类型的数值
  • 把所有键值对聚合为哈希映射

基础实现(兼容性最好)

(require '[clojure.string :as str])

(into {}
      (map (fn [item]
             (let [[key-str val-str] (str/split item #" ")]
               [(keyword key-str) (Integer/parseInt val-str)]))
           ["a 1" "b 2" "c 3"]))

运行上述代码可直接得到目标结果 {:a 1, :b 2, :c 3}。


更简洁的线程宏写法

(require '[clojure.string :as str])

(->> ["a 1" "b 2" "c 3"]
     (map #(str/split % #" "))
     (map (juxt (comp keyword first) (comp #(Integer/parseInt %) second)))
     (into {}))

动态识别值类型的写法(仅适用于可信输入场景)

如果你的值可能包含浮点数、布尔值等多种类型,可以用read-string自动识别类型,无需手动指定转换规则:

(require '[clojure.string :as str])

(into {}
      (map (fn [item]
             (let [[key-str val-str] (str/split item #" ")]
               [(keyword key-str) (read-string val-str)]))
           ["a 1" "b 2" "c 3"]))

内容的提问来源于stack exchange,提问作者leifericf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 08:15:05