gpt4 book ai didi

Scala遍历列表,除了最后一个元素

转载 作者:行者123 更新时间:2023-12-03 18:33:10 25 4
gpt4 key购买 nike

使用 for 循环,如何遍历列表,并能够不遍历列表中的最后一个元素。

就我而言,我不想迭代第一个元素,而是需要向后迭代,这是我所拥有的:

        for( thing <- things.reverse) {
//do some computation iterating over every element;
//break out of loop when first element is reached
}

最佳答案

您可以先删除第一项,然后再将其撤消:

for(thing <- things.drop(1).reverse) {
}

对于列表,如果列表非空, drop(1)tail 相同:
for(thing <- things.tail.reverse) {
}

或者你可以先做相反的事情并使用 dropRight :
for(thing <- things.reverse.dropRight(1)) {
}

如果列表非空,您也可以使用 init:
for(thing <- things.reverse.init) {
}

关于Scala遍历列表,除了最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21565149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com