在 Scala 中,如何在不知道长度的情况下获取从第 n 个元素到列表末尾的列表切片? [英] In Scala, how to get a slice of a list from nth element to the end of the list without knowing the length?
问题描述
我正在寻找一种优雅的方法来从元素 n 开始获取列表的一部分,而无需指定列表的长度.假设我们有一个多行字符串,我将其拆分为多行,然后想要获取从第 3 行开始的所有行的列表:
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:
string.split("\n").slice(3,X) // But I don't know what X is...
这里我真正感兴趣的是是否有办法获取由 split
调用返回的列表的引用,以便可以将其长度替换为 X
在 slice
调用时,有点像一个花哨的 _
(在这种情况下它会读为 slice(3,_.length)
) ?在 python 中,不需要指定切片的最后一个元素.
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 split
call so that its length can be substituted into X
at the time of the slice
call, 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.
当然我可以通过在拆分后使用临时变量来解决这个问题,或者创建一个语法很好的辅助函数,但我只是很好奇.
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.
推荐答案
只需删除不需要的前 n 个元素:
Just drop first n elements you don't need:
List(1,2,3,4).drop(2)
res0: List[Int] = List(3, 4)
或者在你的情况下:
string.split("\n").drop(2)
还有成对的方法 .take(n)
做相反的事情,你可以把它想象成 .slice(0,n)
.
There is also paired method .take(n)
that do the opposite thing, you can think of it as .slice(0,n)
.
如果您需要这两个部分,请使用 .splitAt
:
In case you need both parts, use .splitAt
:
val (left, right) = List(1,2,3,4).splitAt(2)
left: List[Int] = List(1, 2)
right: List[Int] = List(3, 4)
这篇关于在 Scala 中,如何在不知道长度的情况下获取从第 n 个元素到列表末尾的列表切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!