首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从Kotlin中相同大小的MutableList<MutableList<Int>>创建MutableList<MutableList<Boolean>>

如何从Kotlin中相同大小的MutableList<MutableList<Int>>创建MutableList<MutableList<Boolean>>
EN

Stack Overflow用户
提问于 2020-03-06 12:02:20
回答 1查看 265关注 0票数 1

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

第一个想法是这样做:

代码语言:javascript
复制
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
    }
}

但是它当然不起作用,因为它说newmatrixBoolean类型,而不是Int.

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-06 12:22:55

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

代码语言:javascript
复制
// 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)
}

输出:

代码语言:javascript
复制
[[true, true, true], [false, false, false], [false, true, false], [true, false, true]]
[[1, 1, 1], [0, 0, 0], [0, 1, 0], [1, 0, 1]]

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60563687

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档