【问题标题】:Convert vector of lists into vector of vectors将列表向量转换为向量向量
【发布时间】:2018-03-31 22:52:57
【问题描述】:

我在 .txt 文件中有以下数据:

1|John Smith|123 Here Street|456-4567
2|Sue Jones|43 Rose Court Street|345-7867
3|Fan Yuhong|165 Happy Lane|345-4533

我获取数据并使用以下代码将其转换为向量:

(def custContents (slurp "cust.txt"))
(def custVector (clojure.string/split custContents #"\||\n"))
(def testing (into [] (partition 4 custVector )))

这给了我以下向量:

[(1 John Smith 123 Here Street 456-4567) (2 Sue Jones 43 Rose Court Street 
345-7867) (3 Fan Yuhong 165 Happy Lane 345-4533)]

我想把它转换成这样的向量:

[[1 John Smith 123 Here Street 456-4567] [2 Sue Jones 43 Rose Court Street 
345-7867] [3 Fan Yuhong 165 Happy Lane 345-4533]]

【问题讨论】:

    标签: list vector clojure


    【解决方案1】:

    我会做的稍微不同,所以你先把它分成几行,然后处理每一行。它还使正则表达式更简单:

    (ns tst.demo.core
      (:require
        [clojure.string :as str] ))
    
    (def data
    "1|John Smith|123 Here Street|456-4567
    2|Sue Jones|43 Rose Court Street|345-7867
    3|Fan Yuhong|165 Happy Lane|345-4533")
    
      (let [lines       (str/split-lines data)
            line-vecs-1 (mapv #(str/split % #"\|" ) lines)
            line-vecs-2 (mapv #(str/split % #"[|]") lines)]
        ...)
    

    结果:

    lines => ["1|John Smith|123 Here Street|456-4567" 
              "2|Sue Jones|43 Rose Court Street|345-7867" 
              "3|Fan Yuhong|165 Happy Lane|345-4533"]
    
    line-vecs-1 => 
       [["1" "John Smith" "123 Here Street" "456-4567"]
        ["2" "Sue Jones" "43 Rose Court Street" "345-7867"]
        ["3" "Fan Yuhong" "165 Happy Lane" "345-4533"]]
    
    line-vecs-2 => 
       [["1" "John Smith" "123 Here Street" "456-4567"]
        ["2" "Sue Jones" "43 Rose Court Street" "345-7867"]
        ["3" "Fan Yuhong" "165 Happy Lane" "345-4533"]]
    

    请注意,有两种方法可以执行正则表达式。 line-vecs-1 显示了一个正则表达式,其中管道字符在字符串中进行了转义。由于正则表达式在不同平台上有所不同(例如,在 Java 上需要“\|”),line-vecs-2 使用单个字符(管道)的正则表达式类,这回避了转义管道的需要。


    更新

    其他 Clojure 学习资源:

    【讨论】:

    • 我知道这样会更好。谢谢!
    【解决方案2】:
    > (mapv vec testing)
    
    => [["1" "John Smith" "123 Here Street" "456-4567"]
        ["2" "Sue Jones" "43 Rose Court Street" "345-7867"]
        ["3" "Fan Yuhong" "165 Happy Lane" "345-4533"]]
    

    【讨论】:

      猜你喜欢
      • 2011-07-07
      • 2015-07-27
      • 2012-12-24
      • 2013-07-11
      • 2016-07-22
      • 1970-01-01
      相关资源
      最近更新 更多