将列表的向量转换为向量的向量 [英] Convert vector of lists into vector of vectors

查看:374
本文介绍了将列表的向量转换为向量的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.txt文件中包含以下数据:

I have the following data in a .txt file:

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

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

I get the data and convert it to a vector using the following code:

(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)]

我想将其转换为向量的向量,如下所示:

I would like to convert it into a vector of vectors like this:

[[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]]

推荐答案

我会略有不同,因此您首先将其分解成几行,然后处理每一行.这也使正则表达式更简单:

I would do it slightly differently, so you first break it up into lines, then process each line. It also makes the regex simpler:

(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使用单个字符的正则表达式类(管道),从而避免了对管道进行转义的需要.

Note that there are 2 ways of doing the regex. line-vecs-1 shows a regex where the pipe character is escaped in the string. Since regex varies on different platform (e.g. on Java one would need "\|"), line-vecs-2 uses a regex class of a single character (the pipe), which sidesteps the need for escaping the pipe.

更新

Update

其他Clojure学习资源:

Other Clojure Learning Resources:

  • Brave Clojure
  • Clojure CheatSheet
  • ClojureDocs.org
  • Clojure-Doc.org (similar but different)

这篇关于将列表的向量转换为向量的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆