简体   繁体   中英

Scala iterate through list except last element

Using a for loop, how can I iterate through a list, with the ability to not iterate over the very last element in the list.

In my case, I would like to not iterate over the first element, and need to iterate through backwards, here is what I have:

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

You can drop the first item before you reverse it:

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

For lists, drop(1) is the same as tail if the list is non-empty:

for(thing <- things.tail.reverse) {
}

or you could do the reverse first and use dropRight :

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

You can also use init if the list is non-empty:

for(thing <- things.reverse.init) {
}

如Régis所述, for(thing <- things.tail.reverse) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM