【问题标题】:How do I convert a sequence of sequences into a sequence of maps with clojure?如何使用 clojure 将序列序列转换为图序列?
【发布时间】:2015-08-20 21:44:29
【问题描述】:

我正在从每行有两个值的文件中读取数据。每行由代表文件的外部序列中的序列表示。

我想将数据重组为一系列地图以供进一步处理。

我知道如何根据键集和值序列创建映射:

=> (defstruct entry :name :age)
=> (apply struct entry '("John" 34))
{:name "John", :age 34}

但是如何根据一系列值序列创建这样的映射序列呢?

(map (apply struct entry) '(("John" 34) ("Lisa" 41))))

结果:

java.lang.IllegalArgumentException: Don't know how to create ISeq from: clojure.lang.PersistentStructMap$Def

编辑:为清楚起见重命名符号。

【问题讨论】:

    标签: clojure


    【解决方案1】:

    结构已过时,现在优先使用记录。

    (defrecord Person [name age])
    
    (map (partial apply ->Person) '(("John" 34) ("Lisa" 41)))
    

    【讨论】:

      【解决方案2】:

      使用zipmap

      (map (partial zipmap [:name :age]) '(("John" 34) ("Lisa" 41)))
      
      ;-> ({:name "John", :age 34} {:name "Lisa", :age 5})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-03
        相关资源
        最近更新 更多