假设我想遍历Kotlin IntArray
中除第一个元素之外的所有元素。目前,我是这样做的:
fun minimalExample(nums: IntArray): Unit {
for(num in nums.sliceArray(IntRange(1,nums.size-1))) println(num)
}
有没有像Python语言那样的简单语法(我不想指定nums
数组的结束索引):
for (num in nums[1:])
发布于 2020-04-03 23:00:35
我认为你可以使用Kotlin的drop
,它将删除数组的第一个n
元素。
fun minimalExampleWithDrop(nums: IntArray): Unit {
for(num in nums.drop(1)) println(num)
}
minimalExampleWithDrop(intArrayOf(1,2,3,4,5,6))
// 2
// 3
// 4
// 5
// 6
发布于 2020-04-03 23:49:05
以1
作为起始索引的基本for loop
val myList = intArrayOf(1,2,3,4,5,6)
for(i in 1 until myList.size){
Log.d(TAG,"${myList[i]}")
}
或者,因为它是一个IntArray
,所以您可以将其用作Iterator
并跳过像显示的here这样的元素
val iterator = myList.iterator()
// skip an element
if (iterator.hasNext()) {
iterator.next()
}
iterator.forEach {
Log.d(TAG,"it -> $it")
}
发布于 2021-11-01 08:07:32
您也可以使用slice
方法,该方法存在于列表和数组中。下面是这两种情况的示例:
val a = listOf(1, 2, 3, 4)
println(a.slice(1..a.size - 1))
val b = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
println(b.slice(4..5))
这将打印出来:
[2, 3, 4]
[5, 6]
https://stackoverflow.com/questions/61014523
复制相似问题