在 Scala 中获取子数组的正确方法是什么?

我试图在 scala 中获取一个子数组,但是我对正确的方法有些困惑。我最想要的是你在 python 中如何做到这一点:

x = [3, 2, 1]
x[0:2]

但我很确定你不能这么做。

最明显的方法是使用 JavaArrayutil 库。

import java.util.Arrays
val start = Array(1, 2, 3)
Arrays.copyOfRange(start, 0, 2)

但是在 Scala 中使用 Java 库总是让我觉得有点肮脏。我找到的最“不规则”的方法是

def main(args: List[String]) {
val start = Array(1, 2, 3)
arrayCopy(start, 0, 2)
}
def arrayCopy[A](arr: Array[A], start: Int, end: Int)(implicit manifest: Manifest[A]): Array[A] = {
val ret = new Array(end - start)
Array.copy(arr, start, ret, 0, end - start)
ret
}

但有更好的办法吗?

75220 次浏览

You can call the slice method:

scala> Array("foo", "hoo", "goo", "ioo", "joo").slice(1, 4)
res6: Array[java.lang.String] = Array(hoo, goo, ioo)

It works like in python.

Imagine you have an array with elements from a to f

scala> val array = ('a' to 'f').toArray // Array('a','b','c','d','e','f')

Then you can extract a sub-array from it in different ways:

  1. Dropping the first n first elements with drop(n: Int)

    array.drop(2) // Array('c','d','e','f')

  2. Take the first n elements with take(n: Int)

    array.take(4) // Array('a','b','c','d')

  3. Select any interval of elements with slice(from: Int, until: Int). Note that until is excluded.

    array.slice(2,4) // Array('c','d')

    The slice method is stricly equivalent to:
    array.take(4).drop(2) // Array('c','d')

  4. Exclude the last n elements with dropRight(n: Int):

    array.dropRight(4) // Array('a','b')

  5. Select the last n elements with takeRight(n: Int):

    array.takeRight(4) // Array('c','d','e','f')

Reference: Official documentation

An example of extracting specific columns from a 2D Scala Array (original_array):

import scala.collection.mutable.ArrayBuffer


val sub_array = ArrayBuffer[Array[String]]()
val columns_subset: Seq[String] = Seq("ColumnA", "ColumnB", "ColumnC")
val columns_original = original_array(0)


for (column_now <- columns_subset) {
sub_array += original_array.map{_(columns_original.indexOf(column_now))}
}
sub_array