scala 在Scala中,如何在不知道长度的情况下获取从第n个元素到列表末尾的列表切片?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15259250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 05:02:09  来源:igfitidea点击:

In Scala, how to get a slice of a list from nth element to the end of the list without knowing the length?

scala

提问by Mark Silberbauer

I'm looking for an elegant way to get a slice of a list from element n onwards without having to specify the length of the list. Lets say we have a multiline string which I split into lines and then want to get a list of all lines from line 3 onwards:

我正在寻找一种优雅的方法来从元素 n 开始获取列表的一部分,而无需指定列表的长度。假设我们有一个多行字符串,我将其拆分为多行,然后想要获取从第 3 行开始的所有行的列表:

string.split("\n").slice(3,X)       // But I don't know what X is...

What I'm really interested in here is whether there's a way to get hold of a reference of the list returned by the splitcall so that its length can be substituted into Xat the time of the slicecall, kind of like a fancy _(in which case it would read as slice(3,_.length)) ? In python one doesn't need to specify the last element of the slice.

我真正感兴趣的这里是是否有一种方式来获得由返回列表的引用保持split通话,以便其长度可以代入X在时slice通话,有点像一个花哨_(在这种情况下,它会读作slice(3,_.length))?在 python 中,不需要指定切片的最后一个元素。

Of course I could solve this by using a temp variable after the split, or creating a helper function with a nice syntax, but I'm just curious.

当然,我可以通过在拆分后使用临时变量来解决这个问题,或者创建一个具有良好语法的辅助函数,但我只是很好奇。

回答by Val

The right answer is takeRight(n):

正确答案是takeRight(n)

"communism is sharing => resource saver".takeRight(3)
                                              //> res0: String = ver

回答by om-nom-nom

Just drop first n elements you don't need:

只需删除不需要的前 n 个元素:

List(1,2,3,4).drop(2)
res0: List[Int] = List(3, 4)

or in your case:

或者在你的情况下:

string.split("\n").drop(2)

There is also paired method .take(n)that do the opposite thing, you can think of it as .slice(0,n).

还有成对的方法.take(n)做相反的事情,你可以把它想象成.slice(0,n).

In case you need both parts, use .splitAt:

如果您需要这两个部分,请使用.splitAt

val (left, right) = List(1,2,3,4).splitAt(2)
left: List[Int] = List(1, 2)
right: List[Int] = List(3, 4)

回答by haiyang

You can use scala's list method 'takeRight',This will not throw exception when List's length is not enough, Like this:

可以使用scala的list方法'takeRight',当List的长度不够时不会抛出异常,像这样:

val t = List(1,2,3,4,5);
t.takeRight(3);
res1: List[Int] = List(3,4,5)

If list is not longer than you want take, this will not throw Exception:

如果列表不超过您想要的长度,则不会抛出异常:

val t = List(4,5);
t.takeRight(3);
res1: List[Int] = List(4,5)

回答by cloud

get last 2 elements:

获取最后 2 个元素:

List(1,2,3,4,5).reverseIterator.take(2)

List(1,2,3,4,5).reverseIterator.take(2)