首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >将文件和存储元素读取为数组Scala

将文件和存储元素读取为数组Scala
EN

Stack Overflow用户
提问于 2017-03-30 17:26:56
回答 2查看 2K关注 0票数 0

我对Scala很陌生,这是我第一次使用它。我想在一个有两列数字的文本文件中读取,并将每一列项存储在单独的列表或数组中,这些列表或数组必须转换为整数。例如,文本文件如下所示:

代码语言:javascript
代码运行次数:0
运行
复制
1 2 
2 3 
3 4 
4 5 
1 6 
6 7 
7 8 
8 9 
6 10 

我希望将这两列分开,以便将每一列存储在其on列表或数组中。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-30 17:59:15

假设您将该文件命名为“列”,这将是一个解决方案:

代码语言:javascript
代码运行次数:0
运行
复制
    val lines = Source.fromFile("columns").getLines() 
    /* gets an Iterator[String] which interfaces a collection of all the lines in the file*/
    val linesAsArraysOfInts = lines.map(line => line.split(" ").map(_.toInt)) 
    /* Here you transform (map) any line to arrays of Int, so you will get as a result an Interator[Array[Int]] */ 
    val pair: (List[Int], List[Int]) = linesAsArraysOfInts.foldLeft((List[Int](), List[Int]()))((acc, cur) => (cur(0) :: acc._1, cur(1) :: acc._2))
    /* The foldLeft method on iterators, allows you to propagate an operation from left to right on the Iterator starting from an initial value and changing this value over the propagation process. In this case you start with two empty Lists stored as Tuple an on each step you prepend the first element of the array to the first List, and the second element to the second List. At the end you will have to Lists with the columns in reverse order*/

    val leftList: List[Int] = pair._1.reverse
    val rightList: List[Int] = pair._2.reverse
    //finally you apply reverse to the lists and it's done :)
票数 0
EN

Stack Overflow用户

发布于 2017-03-30 17:52:39

以下是一种可能的方法:

代码语言:javascript
代码运行次数:0
运行
复制
val file: String = ??? // path to .txt in String format
val source = Source.fromFile(file)

scala> val columnsTogether = source.getLines.map { line =>
  val nums = line.split(" ") // creating an array of just the 'numbers'
  (nums.head, nums.last) // assumes every line has TWO numbers only
}.toList
columnsTogether: List[(String, String)] = List((1,2), (2,3), (3,4), (4,5), (1,6), (6,7), (7,8), (8,9), (6,10))

scala> columnsTogether.map(_._1.toInt)
res0: List[Int] = List(1, 2, 3, 4, 1, 6, 7, 8, 6)

scala> columnsTogether.map(_._2.toInt)
res1: List[Int] = List(2, 3, 4, 5, 6, 7, 8, 9, 10)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43124584

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档