Python Data Structure 简明教程
Python - 2-D Array
二维数组是数组中的数组。它是一个数组的数组。在此类型的数组中,数据元素的位置用两个索引引用,而不是一个索引。所以它表示一个带有数据行和列的表格。
Two dimensional array is an array within an array. It is an array of arrays. In this type of array the position of an data element is referred by two indices instead of one. So it represents a table with rows an dcolumns of data.
在下面的二维数组示例中,观察到每个数组元素本身也是一个数组。
In the below example of a two dimensional array, observer that each array element itself is also an array.
考虑每天记录温度 4 次的示例。有时记录仪器可能发生故障,我们无法记录数据。4 天的此类数据可以表示为二维数组,如下所示。
Consider the example of recording temperatures 4 times a day, every day. Some times the recording instrument may be faulty and we fail to record data. Such data for 4 days can be presented as a two dimensional array as below.
Day 1 - 11 12 5 2
Day 2 - 15 6 10
Day 3 - 10 8 12 5
Day 4 - 12 15 8 6
上面的数据可以表示为二维数组,如下所示。
The above data can be represented as a two dimensional array as below.
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
Accessing Values
可以使用两个索引访问二维数组中的数据元素。一个索引引用主数组或父数组,另一个索引引用内部数组中数据元素的位置。如果我们只提到一个索引,则会为该索引位置打印整个内部数组。
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.
Example
下面的示例说明了它的工作原理。
The example below illustrates how it works.
from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
print(T[0])
print(T[1][2])
Output
执行上述代码后,将生成以下结果 −
When the above code is executed, it produces the following result −
[11, 12, 5, 2]
10
要打印出整个二维数组,我们可以使用 python for 循环,如下所示。我们使用换行符在不同的行中打印出值。
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.
Inserting Values
我们可以使用 insert() 方法并指定索引,在特定位置插入新的数据元素。
We can insert new data elements at specific position by using the insert() method and specifying the index.
Updating Values
我们可以通过使用数组索引重新分配值来更新整个内部数组或内部数组的某些特定数据元素。
We can update the entire inner array or some specific data elements of the inner array by reassigning the values using the array index.
Deleting the Values
我们可以通过使用带有索引的 del() 方法重新分配值来删除整个内部数组或内部数组的某些特定数据元素。但如果你需要删除其中一个内部数组中的特定数据元素,则可以使用上面描述的更新过程。
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.