繁体   English   中英

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

[英]Scala - How can I split an array of integers into tuples of 2 elements (coordinates)?

我在这里很新,所以如果我把它放在正确的部分中就不会了。 我也是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))
  }
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来避免这种case List(a) => //do something with leftover

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM