Python における行列の転置

PythonPythonBeginner
今すぐ練習

This tutorial is from open-source community. Access the source code

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

線形代数において、行列の転置は、対角線を中心に行列を反転させる演算子です。行列の転置は、行を列に交換することで得られます。Pythonでは、簡単な1行のコードを使って二次元リストを転置することができます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/lists("Lists") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/variables_data_types -.-> lab-13735{{"Python における行列の転置"}} python/comments -.-> lab-13735{{"Python における行列の転置"}} python/lists -.-> lab-13735{{"Python における行列の転置"}} python/tuples -.-> lab-13735{{"Python における行列の転置"}} python/function_definition -.-> lab-13735{{"Python における行列の転置"}} python/build_in_functions -.-> lab-13735{{"Python における行列の転置"}} python/data_collections -.-> lab-13735{{"Python における行列の転置"}} end

行列の転置

transpose(lst) という関数を書きます。この関数は二次元リストを引数として受け取り、与えられたリストの転置を返します。

この問題を解くには、次の手順に従ってください。

  • *lst を使って、与えられたリストをタプルとして取得します。
  • zip()list() を組み合わせて、与えられた二次元リストの転置を作成します。
def transpose(lst):
  return list(zip(*lst))
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
## [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]

まとめ

このチャレンジでは、Pythonを使って二次元リストを転置する方法を学びました。行列の転置は、行を列に交換することで得られます。この技術を使うと、データ分析や機械学習など、さまざまなアプリケーションでデータを操作することができます。