Python-data-structure-python-2darray

提供:Dev Guides
移動先:案内検索

Python-2D配列

2次元配列は、配列内の配列です。 これは配列の配列です。 このタイプの配列では、データ要素の位置は1つではなく2つのインデックスによって参照されます。 そのため、行とデータのd列を持つテーブルを表します。 以下の2次元配列の例では、各配列要素自体も配列であることに注意してください。

毎日4回、温度を記録する例を考えてみましょう。 記録機器に障害が発生し、データを記録できない場合があります。 このような4日間のデータは、次のように2次元配列として表示できます。

Day 1 - 11 12 5 2
Day 2 - 15 6 10
Day 3 - 10 8 12 5
Day 4 - 12 15 8 6

上記のデータは、次のように2次元配列として表すことができます。

T = [[Accessing Values in a Two Dimensional Array

The data elements in two dimesnional arrays can be accessed using two indices. One index referring to the main or parent array and another index referring to the position of the data element in the inner array.
If we mention only one index then the entire inner array is printed for that index position. The example below illustrates how it works.

[source,prettyprint,notranslate]

配列インポートから*

T = [[print(T [0])

print(T [1] [2])

When the above code is executed, it produces the following result −

[source,result,notranslate]

10

To print out the entire two dimensional array we can use python for loop as shown below. We use end of line to print out the values in different rows.

[source,prettyprint,notranslate]

配列インポートから*

T = [[Tのrの場合:rのcの場合:print(c、end = "")print()

When the above code is executed, it produces the following result −

[source,result,notranslate]

11 12 5 2 15 6 10 10 8 12 5 12 15 8 6

=== Inserting Values in Two Dimensional Array

We can insert new data elements at specific position by using the insert() method and specifying the index.

In the below example a new data element is inserted at index position 2.

[source,prettyprint,notranslate]

配列からインポート* T = [[T.insert(2、[0,5,11,13,6])

Tのrの場合:rのcの場合:print(c、end = "")print()

When the above code is executed, it produces the following result −

[source,result,notranslate]

11 12 5 2 15 6 10 0 5 11 13 6 10 8 12 5 12 15 8 6

=== Updating Values in Two Dimensional Array

We can update the entire inner array or some specific data elements of the inner array by reassigning the values using the array index.

[source,prettyprint,notranslate]

配列インポートから*

T = [[T [2] = [11,9] T [0] [3] = 7 Tのrの場合:rのcの場合:print(c、end = "")print()

When the above code is executed, it produces the following result −

[source,result,notranslate]

11 12 5 7 15 6 10 11 9 12 15 8 6

=== Deleting the Values in Two Dimensional Array

We can delete the entire inner array or some specific data elements of the inner array by reassigning the values using the del() method with index. But in case you need to remove specific data elements in one of the inner arrays, then use the update
process described above.

[source,prettyprint,notranslate]

配列からインポート* T = [[del T [3]

Tのrの場合:rのcの場合:print(c、end = "")print()

When the above code is executed, it produces the following result −

[source,result,notranslate]

11 12 5 2 15 6 10 10 8 12 5