我正在寻找一种优雅的方式来从元素n开始获取一列列表,而不必指定列表的长度。 让我们说我们有一个多行字符串,我分成几行,然后想要从第3行开始得到所有行的列表:
string.split("\n").slice(3,X) // But I don't know what X is...我真正感兴趣的是,是否有办法获得split调用返回的列表的引用,以便在split调用时可以将其长度替换为X ,这有点像花式的_ (在这种情况下,它会读作slice(3,_.length) )? 在python中,不需要指定切片的最后一个元素。
当然,我可以通过在分割后使用一个临时变量来解决这个问题,或者用一个很好的语法创建一个辅助函数,但我只是好奇而已。
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...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个元素即可:
List(1,2,3,4).drop(2) res0: List[Int] = List(3, 4)或者在你的情况下:
string.split("\n").drop(2)也有配对方法。 .take(n)做相反的事情,你可以把它看作.slice(0,n) 。
如果你需要两个部分,使用.splitAt :
val (left, right) = List(1,2,3,4).splitAt(2) left: List[Int] = List(1, 2) right: List[Int] = List(3, 4)Just drop first n elements you don't need:
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).
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)更多推荐
发布评论