Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Kotlinで二次元リストの行と列を入れ替える

Kotlin で二次元リストの行と列を入れ替える関数が欲しくなったとき、
大変参考になる JavaScript の記事 を発見しましたので、Kotlin版を作ってみました。

関数

function
fun <T> transpose(list: List<List<T>>): List<List<T>> =
    list.first().mapIndexed { index, _ ->
        list.map { row -> row[index] }
    }

使用例

sample
fun main(args: Array<String>) {
    val list1: List<List<Char>> = listOf(
        listOf('a', 'b', 'c'),
        listOf('d', 'e', 'f'),
        listOf('g', 'h', 'i')
    )

    println(list1)
    // => [[a, b, c], [d, e, f], [g, h, i]]

    println(transpose(list1))
    // => [[a, d, g], [b, e, h], [c, f, i]]

    val list2: List<List<Int>> = listOf(
        listOf(1, 2, 3),
        listOf(4, 5, 6),
        listOf(7, 8, 9)
    )

    println(list2)
    // => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

    println(transpose(list2))
    // => [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
}
jz4o
kntk_team
某SIerのチームです。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away