6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonとJavaScriptでリスト(List)を転置させるときの違い

Last updated at Posted at 2024-12-09

Pythonでリストを転置

def transpose(matrix):
    return [list(row) for row in zip(*matrix)]

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

transposed_matrix = transpose(matrix)
print(transposed_matrix)

説明:

  • zip(*matrix) は、各行の対応する要素をまとめてタプルにします。
  • リスト内包表記 [list(row) for row in zip(*matrix)] により、各タプルをリストに変換し、新しいリストとして返します。
  • numpyに変換して、transpose関数を使うのも手。

JavaScriptでリストを転置

function transpose(matrix) {
    return matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex]));
}

const matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

const transposedMatrix = transpose(matrix);
console.log(transposedMatrix);

説明:

  • matrix[0].map((_, colIndex) => matrix.map(row => row[colIndex])) は、各列の要素を取り出し、新しい配列を作成します。
  • 最初の map 関数は列のインデックスを提供し、内側の map 関数が各行の要素を収集します。
6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?