【问题标题】:Scala - How can I split an array of integers into tuples of 2 elements (coordinates)?Scala - 如何将整数数组拆分为 2 个元素(坐标)的元组?
【发布时间】:2018-07-14 20:24:53
【问题描述】:

我在这里很新,所以如果我把它放在正确的部分,我就不是。我对 Scala 也很陌生。

无论如何,所以我正在尝试从文本文件中读取数字(我猜它们在这里是字符串)并将它们分成对,按照它们被读取的顺序,但我无法处理:

  • 新行
  • 将一组数字拆分成对

这是我的代码:

def main(args: Array[String]): Unit = {
  val file = Source.fromFile("/Users/donatkapesa/Desktop/poly.txt")
  val fileLines = file.getLines()

  while(fileLines.hasNext && !fileLines.isEmpty) {
    val array = fileLines.next.split(" ")
    //this doesn't take care of new lines. I have tried .split(" +") and .split("\\s+")

    // change the array elements to integers
    val intArray = array.map(array => array.toInt)

    // split array elements into tuples. But it doesn't work
    val coordinates = intArray.map(case Array(x,y) => (x,y))
  }

【问题讨论】:

    标签: arrays scala list tuples


    【解决方案1】:
    io.Source
      .fromFile("poly.txt")    //open file
      .getLines                //read line-by-line
      .flatMap(_.split(" +"))  //split each line on the spaces
      .grouped(2)              //pair all strings /*sliding(2,2) also works*/
      .map{case List(a,b) => (a.toInt, b.toInt)}  //convert to Iterator[(Int,Int)]
      .toList                  //convert from Iterator to List (if desired)
    

    请注意,从StringInt 的转换在这里并不安全。应检查字符串以确保它们仅包含数字字符。我还做了一个映射字符串对的捷径。如果有奇数个字符串进行转换,那么这个map() 将抛出一个MatchError。这可以通过添加case List(a) => //do something with leftover 来避免。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-30
      • 2016-02-12
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多