Python:配列を作成して使用する-仕組み
Pythonを使用してプログラミングする場合、配列をすばやく見つけます。 このPythonガイドは、それらの作成方法と使用方法を示しています。 Pythonでのプログラミングはそれほど難しくないからです。
Pythonでリストを作成する
Javaのような古典的な「配列」はPythonには存在しません。 ただし、同様の方法で機能する、いわゆるリストを作成できます。 モジュールごとに配列を後付けすることもできます。これについては、2番目の段落で説明します。
- たとえば、コマンド「a = [1、2、3]」を使用してリストを作成できます。 このリストには3つの整数値が含まれます。
- たとえば、「print(a [0])」コマンドを使用して特定の値を出力できます。 この場合、コンピューターは0からカウントを開始するため、数値1が出力されます。 同じ方法でリストのエントリを変更することもできます: "a [0] = 15"。
- 多次元リストを作成することもできます。 この例は、コマンド「b = [[1、2、3]、[4、5、6]]」です。 コマンド「print(b [1] [0])」は、数値4を出力します。
- 「print(a [2:5])」でリストの特定の領域を印刷するか、複数のリストエントリを同時に再定義できます(コマンド:「a [0:2] = [0, 1]」)。
- forループと連携したリストは非常に実用的です。 "for i in a:"ループでは、反復時にリスト内の各値を1回(1つずつ)想定します。 各実行後に変更されます。 ただし、注意してください。forループを使用して2次元リストを反復処理する場合、反復可能要素もリストです。 ここでは、forループ内にforループが必要です。
- リストに加えて、Pythonで配列を使用する別の方法があります。 これを行うには、まず適切なモジュールをインストールする必要があります。
Pythonの配列:最初にNumPyモジュールをインストールします
アレイの作成を開始する前に、まずNumPyモジュールをインストールする必要があります。 これは通常、プリインストールされていないためです。 Windowsでの動作は次のとおりです。
- キーの組み合わせ[Windowsキー] + [R]とコマンド「CMD」を使用して、PCでコマンドプロンプトを開きます。
- 次に、ディレクトリの変更コマンドを使用して、Pythonシステムフォルダーの「スクリプト」サブフォルダーに移動します。これを行うには、「cd C:\ Users \ yourusername \ AppData \ Local \ Programs \ Python \ Python36 \ Scripts」と入力します。 ただし、このサブフォルダーへのパスは、オペレーティングシステムのバージョンとPythonのバージョンによって異なる場合があることに注意してください。 そのため、フォルダの場所を事前に確認してください。
- 次に、「pip install numpy」コマンドを実行してNumPyをインストールします。
Pythonガイド:配列を作成する
これで、NumPyモジュールを使用して簡単に配列を作成できます。
- まず、「numpy as npをインポート」コマンド(引用符なし)でNumPyモジュールをインポートする必要があります。
- これで、コマンド「x = np.array([1, 2, 3, 4])」を使用して最初の配列を作成できます。 この場合、配列は変数「x」の下に保存されます。
- 「print(x)」コマンドを使用して、テスト用にこの配列を簡単に出力できます。
- 複数の「ディメンション」を持つ配列を作成することもできます。 この例は、「y = np.array([[1、2、3]、[4、5、6]、[7、8、9]])」です。 この配列を「print(y)」で印刷すると、3x3フィールドが印刷されていることがわかります。 最初の行では、番号1、2、3は2番目の4、5、6にあり、最後の7、8、9にあります。
- 必要に応じて、np.arange(10)コマンドを使用して、0〜9のすべての整数を含む配列を作成できます。
- コマンド「np.arange(2、10、dtype = np.float)」は、2から9までのすべての整数を浮動小数点数(「float」)で含む配列を作成します。 したがって、これには2.0、3.0、4.0などの数字が含まれます。
- たとえば、「np.arange(2、3、0.1)」コマンドを使用して、2.0〜2.9の数値を含む配列を作成できます。 値は、0.1、つまり2.0、2.1、2.2などのステップで作成されます。
- もう1つの実用的なコマンドは「np.linspace(1、2、3)」です。 このコマンドは、1〜2の3つの数値を含む配列を出力します。 ここで特別なことは、数字が常に同じ距離だけ離れていることです。 この場合、数値1.0、1.5、および2.0が出力されます。
- 最後に、コマンド「np.indices((4、3))」があります。 これにより、多くの次元を持つ配列が作成され、各次元は前の次元のバリエーションです。 この場合、それぞれ4行の2つのディメンションが作成されます。 両方のディメンションには、行ごとに3つの数値があります。
CHIPガイドのPythonに関するその他のヒント
ヒント:Pythonプログラミング言語のトピックページには、プログラミングに関する詳細なチュートリアルがあります。 ここでは、たとえば、rangeとxrangeの使用方法を示します。