如何在Clojure中将列表组成的Vector转换为Vector of Vectors
把列表组成的Vector转换为Vector of Vectors的Clojure解决方案
嘿,这个问题其实很容易搞定,咱们先捋下你现有的代码逻辑:你已经成功把文本文件内容分割成扁平序列,再通过partition 4把每4个元素归为一组,但partition返回的是惰性序列的列表,所以最终得到的是包含列表的Vector。要把里面每个列表都转成Vector,只需要加一步简单转换就行。
方法1:用mapv+vec直接转换
vec函数可以把任何可序列化对象(比如partition返回的列表)转换成Vector,而mapv是map的变体,它会直接返回Vector而非惰性序列,刚好匹配你的需求:
(def custContents (slurp "cust.txt")) (def custVector (clojure.string/split custContents #"\||\n")) ;; 修改这一行,把每个分区的列表转成Vector (def testing (mapv vec (partition 4 custVector)))
方法2:结合into与Transducer写法
如果你更习惯用Transducer的流式处理风格,也可以在into的转换流程里加入map vec,让整个处理过程更连贯:
(def testing (into [] (map vec) (partition 4 custVector)))
最终效果验证
执行完上面的代码后,你的testing变量就会变成完全由Vector组成的Vector,结构大概是这样:
[[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"]]
内容的提问来源于stack exchange,提问作者No Name
相关产品推荐
相关产品推荐

