数値リストの定義
このステップでは、Python で数値リストを定義する方法を学びます。リストはアイテムの集合であり、この場合は数値を含むリストに焦点を当てます。リストは Python の基本的なデータ構造であり、データの順序付けられたシーケンスを格納して操作するために使用されます。
まず、VS Code エディタを使用して、~/project
ディレクトリに numeric_lists.py
という名前の新しい Python ファイルを作成しましょう。
~/project/numeric_lists.py
次に、エディタで numeric_lists.py
を開き、整数のリストを定義するために以下のコードを追加します。
## Define a list of integers
integer_list = [1, 2, 3, 4, 5]
## Print the list to the console
print(integer_list)
ファイルを保存します。次に、VS Code でターミナルを開き、~/project
ディレクトリに移動します。デフォルトではすでにこのディレクトリにいるはずです。次に、以下のコマンドを使用して Python スクリプトを実行します。
python numeric_lists.py
以下の出力が表示されるはずです。
[1, 2, 3, 4, 5]
次に、浮動小数点数(小数)のリストを定義しましょう。
numeric_lists.py
ファイルを変更して以下を追加します。
## Define a list of floating-point numbers
float_list = [1.0, 2.5, 3.7, 4.2, 5.9]
## Print the list to the console
print(float_list)
ファイルを保存し、再度スクリプトを実行します。
python numeric_lists.py
以下の出力が表示されるはずです。
[1.0, 2.5, 3.7, 4.2, 5.9]
整数と浮動小数点数の混合を含むリストも作成できます。
numeric_lists.py
ファイルを変更して以下を追加します。
## Define a list of mixed numbers (integers and floats)
mixed_list = [1, 2.0, 3, 4.5, 5]
## Print the list to the console
print(mixed_list)
ファイルを保存し、再度スクリプトを実行します。
python numeric_lists.py
以下の出力が表示されるはずです。
[1, 2.0, 3, 4.5, 5]
おめでとうございます!Python で数値リストを正常に定義して出力しました。これは、Python で数値データを扱うための基本的なステップです。