Scala 如何通过索引获取子列表 [英] Scala How to get sublist by index

查看:47
本文介绍了Scala 如何通过索引获取子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 List(1 ,2 ,3 ,4 ,5) 并试图通过以下方式从中获取一个子列表: List(3, 4) :

I have a List(1 ,2 ,3 ,4 ,5) and trying to get a sublist: List(3, 4) from it by the following way:

List(1 ,2 ,3 ,4 ,5).slice(this.size - 3 , this.size - 1 )

但是我遇到了一个错误

error: value size is not a member of object

如何像在 Java 中一样在 Scala 中使用this"参数.是否有其他方法可以实现目标.非常感谢.

How can I use "this" parameter in Scala just like in Java. Are there other ways to achieve the goal. Thank you so much.

推荐答案

你应该先声明列表,然后使用它的名字list引用列表,而不是this:

You should first declare the list, and then refer to the list using its name list, not this:

val list = List(1 ,2 ,3 ,4 ,5)
list.slice(list.size -3, list.size -1)

如果你真的想在一行中做到这一点,那么使用reverse,但效率不高:

If you really want to do this in one line, then use reverse, but it's not very efficient:

List(1 ,2 ,3 ,4 ,5).reverse.slice(1, 3).reverse

顺便说一下,该代码在 Java 中也无效.this 指的是封闭对象,而不是列表.

By the way, that code wouldn't be valid in Java either. this refers to the enclosing object, not to the list.

这篇关于Scala 如何通过索引获取子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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