在Scala中,如何在不知道长度的情况下从第n个元素到列表的末尾获得一个列表的切片?(In Scala, how to get a slice of a list from nth element t

系统教程 行业动态 更新时间:2024-06-14 17:01:34
在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行开始得到所有行的列表:

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)

更多推荐

本文发布于:2023-04-20 18:39:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/85c6dd72c069b2f85b0b283d1cd14dfa.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表   末尾   切片   长度   情况下

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!