在 Scala 中获取子数组的正确方法是什么? [英] What is the correct way to get a subarray in Scala?

查看:65
本文介绍了在 Scala 中获取子数组的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to get a subarray in scala, and I am a little confused on what the proper way of doing it is. What I would like the most would be something like how you can do it in python:

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

但我很确定你不能这样做.

but I am fairly certain you cannot do this.

最明显的方法是使用 Java Arrays util 库.

The most obvious way to do it would be to use the Java Arrays util library.

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

但是在 Scala 中使用 Java 库总是让我觉得有点脏.我发现的最scalaic"的方式是

But it always makes me feel a little dirty to use Java libraries in Scala. The most "scalaic" way I found to do it would be

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
}

但是有更好的方法吗?

推荐答案

可以调用slice方法:

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)

它在 Python 中的工作原理.

It works like in python.

这篇关于在 Scala 中获取子数组的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆