如何在 <Int><Boolean>Kotlin 中创建相同大小的可变列表<可变列表<可变列表>>

  • 本文关键字:列表 Kotlin Int Boolean 创建 kotlin
  • 更新时间 :
  • 英文 :


我想知道如何创建与给定matrix = MutableList<MutableList<Boolean>>大小相同的newmatrix = MutableList<MutableList<Int>>。我特别希望newmatrix为零,这可以通过循环来实现
最初的想法是这样做:

var newmatrix = matrix
// tworzymy macierz równą zero
for (k in 0..matrix.indices.last) {
    for (l in 0..matrix[0].indices.last) {
        newmatrix[k][l] = 0
    }
}

但它当然不起作用,因为它说newmatrix的类型是Boolean,而不是Int。。。

您可以编写一个扩展函数,将MutableList<Boolean>转换为MutableList<Int>,然后在列表列表中使用forEach来转换每个项目:

// extension function for an Int-representation of a Boolean-list
fun MutableList<Boolean>.toIntList(): MutableList<Int> {
    var result: MutableList<Int> = mutableListOf()
    this.forEach { it -> if (it) { result.add(1) } else { result.add(0) } }
    return result
}
fun main(args: Array<String>) {
    // example Boolean-matrix
    var matrix: MutableList<MutableList<Boolean>> = mutableListOf(
            mutableListOf(true, true, true),
            mutableListOf(false, false, false),
            mutableListOf(false, true, false),
            mutableListOf(true, false, true)
    )
    // provide the structure for the result
    val newMatrix: MutableList<MutableList<Int>> = mutableListOf()
    // for each Boolean-list in the source list add the result of toIntList() to the result
    matrix.forEach { it -> newMatrix.add(it.toIntList()) }
    // print the source list
    println(matrix)
    // print the resulting Int list
    println(newMatrix)
}

输出:

[[true, true, true], [false, false, false], [false, true, false], [true, false, true]]
[[1, 1, 1], [0, 0, 0], [0, 1, 0], [1, 0, 1]]

可能有不同甚至更好的转换方式,但这似乎已经足够了。

最新更新