logo

Python – 指定された長さの空の配列を初期化します

みなさんご存じのとおり 配列 連続したメモリ位置に保存されている項目のコレクションです。 Python では、 リスト ( ダイナミックアレイ ) は配列として扱うことができます。この記事では、特定のサイズの空の配列を初期化する方法を学びます。空のリストを作成するさまざまな Python の方法を見てみましょう。 パイソン ある程度の大きさのあるもの。

Python – 指定された長さの空の配列を初期化します

以下は、Python で指定された長さの空の配列を初期化するメソッドです。



リストするJava配列
  • * 演算子の使用
  • リスト内包表記の使用
  • For ループの使用
  • 使用する ナムピー
  • repeat() メソッドの使用

方法 1: * 演算子を使用して空の配列を初期化する

この例では、 アスタリスク (*) 演算子。

Python3
# initializes all the 10 spaces with 0’s a = [0] * 10 print('Intitialising empty list with zeros: ', a) # initializes all the 10 spaces with None b = [None] * 10 print('Intitialising empty list of None: ', b) # initializes a 4 by 3 array matrix all with 0's c = [[0] * 4] * 3 print('Intitialising 2D empty list of zeros: ', c) # empty list which is not null, it's just empty. d = [] print('Intitialising empty list of zeros: ', d)>

出力
Creating empty list contains zeros: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] Creating empty list of None: [None, None, None, None, None, None, None, None, None, None] Creating 2D empty list of zeros: [[0, 0,...>

方法 2: リスト内包表記を使用して、Python で特定のサイズの空のリストを作成する

この例では Python を使用しています リストの内包表記 1D および 2D の空の配列の場合。

Python3
# initialize the spaces with 0’s with  # the help of list comprehensions a = [0 for x in range(10)] print(a) b = [[0] * 4 for i in range(3)] print(b)>

出力
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]>

方法 3: ループを使用して Python で特定のサイズの空のリストを作成する

この例では、 Python ループ 1D および 2D の空の配列の場合。



Python3
b= [] for x in range(5): b.append([[]]) print(b) c = [] for x in range(5): c.append(0) print(c)>

出力
[[[]], [[]], [[]], [[]], [[]]] [0, 0, 0, 0, 0]>

方法 4: を使用して空の配列を初期化する ナンピー

このメソッドでは、 Numpy モジュール を使用して 1D および 2D サイズの空の行列を生成するには np.empty()

VBとVBネット
Python3
import numpy # create a simple array with numpy empty() a = numpy.empty(5, dtype=object) print(a) # create multi-dim array by providing shape matrix = numpy.empty(shape=(2, 5), dtype='object') print(matrix)>

出力
[None None None None None] [[None None None None None] [None None None None None]]>

方法 5:repeat() メソッドを使用して空の配列を初期化する

このメソッドでは、 itertools モジュールのrepeat() 関数を使用して、同じ値を一定回数返す新しい反復子を作成できます。これを使用すると、None の値と必要な長さを指定することで、特定のサイズの空の配列を作成できます。

Python3
import itertools #Initialize empty array with length 10 filled with 0's a = list(itertools.repeat(0, 10)) print(a) #Initialize 2D empty array with 3 rows and 4 columns filled with 0's b = [list(itertools.repeat(0, 4)) for i in range(3)] print(b)>

出力
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]>

この方法の時間計算量は O(n) で、補助空間は O(n) です。ここで、n は配列の必要な長さです。



参照 : Python でリストする

Javaで文字列を整数に変換する