我需要使用外部文件复制此数组定义的结果。
scala> val data = Seq(Array(Array(1, 2), Array(3)),Array(Array(1), Array(3, 2), Array(1, 2)),Array(Array(1, 2), Array(5)),Array(Array(6)))
data: Seq[Array[Array[Int]]] = List(Array(Array(1, 2), Array(3)), Array(Array(1), Array(3, 2), Array(1, 2)), Array(Array(1, 2), Array(5)), Array(Array(6)))
我尝试创建 testdataI.txt 文件,但无法使其工作。
testdataI.txt ->
1,2
3
1
3,2
1,2
1,2
5
6
这是我使用 io.Source 进行转换时的结果:
import scala.io.Source
scala> val data = Seq(Source.fromFile("/tmp/testdataI.txt").getLines().map(_.split(",").map(_.trim.toInt)).toArray)
data: Seq[Array[Array[Int]]] = List(Array(Array(1, 2), Array(3), Array(1), Array(3, 2), Array(1, 2), Array(1, 2), Array(5), Array(6)))
结果应该如下所示(一系列多维数组)
data: Seq[Array[Array[Int]]] = List(Array(Array(1, 2), Array(3)), Array(Array(1), Array(3, 2), Array(1, 2)), Array(Array(1, 2), Array(5)), Array(Array(6)))
我找到了很多多维数组信息,但没有找到适合此特定情况的信息。
非常感谢,
弗雷迪·戈麦斯
最佳答案
不知道为什么要这样构造值,但可以这样做:
scala> import scala.io.Source
import scala.io.Source
scala> val take = List(2, 3, 2, 1)
take: List[Int] = List(2, 3, 2, 1)
scala> val data = Source.fromFile("/tmp/testdataI.txt").getLines().map(_.split(",").map(_.trim.toInt).toList).toList
data: List[List[Int]] = List(List(1, 2), List(3), List(1), List(3, 2), List(1, 2), List(1, 2), List(5), List(6))
scala> def awesomeGrouped(ungrouped: List[List[Int]], take: List[Int]): List[List[List[Int]]] = take match {
| case Nil => Nil
| case t :: ts => ungrouped.take(t) :: awesomeGrouped(ungrouped.drop(t), ts)
| }
awesomeGrouped: (ungrouped: List[List[Int]], take: List[Int])List[List[List[Int]]]
scala> def fixTypes(grouped: List[List[List[Int]]]) = grouped.map(_.map(_.toArray).toArray)
fixTypes: (sorted: List[List[List[Int]]])List[Array[Array[Int]]]
scala> fixTypes(awesomeGrouped(data, take))
res0: List[Array[Array[Int]]] = List(Array(Array(1, 2), Array(3)), Array(Array(1), Array(3, 2), Array(1, 2)), Array(Array(1, 2), Array(5)), Array(Array(6)))
让大家不安的部分是你选择的take
列表分布;看起来很随意。
注意,我专门添加了 fixTypes
函数来返回您想要的确切返回类型。但数组并不是 Scala 的惯用用法;你确定你需要它们吗?如果没有,只需删除 fixTypes
函数和调用。
关于java - Scala 从文件读取多维数组 [Array[Array[Int]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37197506/