Scala - 如何将整数数组拆分为2个元素(坐标)的元组?

时间:2018-02-05 01:34:38

标签: arrays scala list tuples

我在这里很新,所以如果我把它放在正确的部分,我就不会这样做。我对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))
  }

1 个答案:

答案 0 :(得分:2)

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可以避免这种情况。