Mục lục bài viết
Update: 2022-03-12 06:50:15,Bạn Cần kiến thức và kỹ năng về Python print 2d list as table. You trọn vẹn có thể lại Comments ở cuối bài để Mình đc tương hỗ.
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.
Tóm lược đại ý quan trọng trong bài
In the below example of a two dimensional array, observer that each array element itself is also an array.
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]]
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.
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])
When the above code is executed, it produces the following result −
[11, 12, 5, 2]
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.
from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
for r in T:
for c in r:
print(c,end = ” “)
print()
When the above code is executed, it produces the following result −
11 12 5 2
15 6 10
10 8 12 5
12 15 8 6
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.
from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
T.insert(2, [0,5,11,13,6])
for r in T:
for c in r:
print(c,end = ” “)
print()
When the above code is executed, it produces the following result −
11 12 5 2
15 6 10
0 5 11 13 6
10 8 12 5
12 15 8 6
We can update the entire inner array or some specific data elements of the inner array by reassigning the values using the array index.
from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
T[2] = [11,9]
T[0][3] = 7
for r in T:
for c in r:
print(c,end = ” “)
print()
When the above code is executed, it produces the following result −
11 12 5 7
15 6 10
11 9
12 15 8 6
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.
from array import *
T = [[11, 12, 5, 2], [15, 6,10], [10, 8, 12, 5], [12,15,8,6]]
del T[3]
for r in T:
for c in r:
print(c,end = ” “)
print()
When the above code is executed, it produces the following result −
11 12 5 2
15 6 10
10 8 12 5
for row in A:
for val in row:
print ‘:4’.format(val),
print
Python provides many ways to create 2-dimensional lists/arrays. However one must know the differences between these ways because they can create complications in code that can be very difficult to trace out. Lets start by looking at common ways of creating 1d array of size N initialized with 0s.
Method 1a
Method 1b
arr = [0 for i in range(N)]
Extending the above we can define 2-dimensional arrays in the following ways.
Method 2a
Output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Method 2b
arr = [[0 for i in range(cols)] for j in range(rows)]
Output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Method 2c
Output:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
Both the ways give seemingly same output as of now. Lets change one of the elements in the array of method 2a and method 2b.
arr = [[0 for i in range(cols)] for j in range(rows)]
Output:
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
We expect only the first element of first row to change to 1 but the first element of every row gets changed to 1 in method 2a. This peculiar functioning is because Python uses shallow lists which we will try to understand.In method 1a, Python doesn’t create 5 integer objects but creates only one integer object and all the indices of the array arr point to the same int object as shown.
If we assign the 0th index to a another integer say 1, then a new integer object is created with the value of 1 and then the 0th index now points to this new int object as shown below
Similarly, when we create a 2d array as “arr = [[0]*cols]*rows” we are essentially the extending the above analogy. 1. Only one integer object is created. 2. A single 1d list is created and all its indices point to the same int object in point 1. 3. Now, arr[0], arr[1], arr[2] …. arr[n-1] all point to the same list object above in point 2.The above setup can be visualized in the image below.
Now lets change the first element in first row of “arr” as arr[0][0] = 1=> arr[0] points to the single list object we created we above.(Remember arr[1], arr[2] …arr[n-1] all point to the same list object too) => The assignment of arr[0][0] will create a new int object with the value 1 and arr[0][0] will now point to this new int object.(and so will arr[1][0], arr[2][0] …arr[n-1][0])This can be clearly seen in the below image.
So when 2d arrays are created like this, changing values at a certain row will effect all the rows since there is essentially only one integer object and only one list object being referenced by the all the rows of the array.As you would expect, tracing out errors caused by such usage of shallow lists is difficult. Hence the better way to declare a 2d array is
arr = [[0 for i in range(cols)] for j in range(rows)]
This method creates 5 separate list objects unlike method 2a. One way to check this is using the ‘is’ operator which checks if the two operands refer to the same object.
arr = [[0 for i in range(cols)] for j in range(rows)]
Article Tags :
An array is a collection of linear data structures that contain all elements of the same data type in contiguous memory space. It is like a container that holds a certain number of elements that have the same data type. An array’s index starts at 0, and therefore, the programmer can easily obtain the position of each element and perform various operations on the array. In this section, we will learn about 2D (two dimensional) arrays in Python.
A 2D array is an array of arrays that can be represented in matrix form like rows and columns. In this array, the position of data elements is defined with two indices instead of a single index.
Syntax
Array_name = [rows][columns] # declaration of 2D array Arr-name = [ [m1, m2, m3, … . mn], [n1, n2, n3, … .. nn] ]
Where m is the row and n is the column of the table.
In Python, we can access elements of a two-dimensional array using two indices. The first index refers to the indexing of the list and the second index refers to the position of the elements. If we define only one index with an array name, it returns all the elements of 2-dimensional stored in the array.
Let’s create a simple program to understand 2D (two dimensional) arrays in Python.
2dSimple.py
Student_dt = [ [72, 85, 87, 90, 69], [80, 87, 65, 89, 85], [96, 91, 70, 78, 97], [90, 93, 91, 90, 94], [57, 89, 82, 69, 60] ]
#print(student_dt[])
print(Student_dt[1]) # print all elements of index 1
print(Student_dt[0]) # print all elements of index 0
print(Student_dt[2]) # print all elements of index 2
print(Student_dt[3][4]) # it defines the 3rd index and 4 position of the data element.
Output:
In the above example, we passed 1, 0, and 2 as parameters into 2D array that prints the entire row of the defined index. And we have also passed student_dt[3][4] that represents the 3rd index and 4th position of a 2-dimensional array of elements to print a particular element.
Program.py
# write a program to traverse every element of the two-dimensional array in Python.
Student_dt = [ [72, 85, 87, 90, 69], [80, 87, 65, 89, 85], [96, 91, 70, 78, 97], [90, 93, 91, 90, 94], [57, 89, 82, 69, 60] ]
# Use for loop to print the entire elements of the two dimensional array.
for x in Student_dt: # outer loop
for i in x: # inner loop
print(i, end = ” “) # print the elements
print()
Output:
We can insert elements into a 2 D array using the insert() function that specifies the element’ index number and location to be inserted.
Insert.py
# Write a program to insert the element into the 2D (two dimensional) array of Python.
from array import * # import all package related to the array.
arr1 = [[1, 2, 3, 4], [8, 9, 10, 12]] # initialize the array elements.
print(“Before inserting the array elements: “)
print(arr1) # print the arr1 elements.
# Use the insert() function to insert the element that contains two parameters.
arr1.insert(1, [5, 6, 7, 8]) # first parameter defines the index no., and second parameter defines the elements
print(“After inserting the array elements “)
for i in arr1: # Outer loop
for j in i: # inner loop
print(j, end = ” “) # print inserted elements.
print()
Output:
In a 2D array, the existing value of the array can be updated with a new value. In this method, we can change the particular value as well as the entire index of the array. Let’s understand with an example of a 2D array, as shown below.
Create a program to update the existing value of a 2D array in Python.
Update.py
from array import * # import all package related to the array.
arr1 = [[1, 2, 3, 4], [8, 9, 10, 12]] # initialize the array elements.
print(“Before inserting the array elements: “)
print(arr1) # print the arr1 elements.
arr1[0] = [2, 2, 3, 3] # update the value of the index 0
arr1[1][2] = 99 # define the index [1] and position [2] of the array element to update the value.
print(“After inserting the array elements “)
for i in arr1: # Outer loop
for j in i: # inner loop
print(j, end = ” “) # print inserted elements.
print()
Output:
In a 2- D array, we can remove the particular element or entire index of the array using del() function in Python. Let’s understand an example to delete an element.
Delete.py
from array import * # import all package related to the array.
arr1 = [[1, 2, 3, 4], [8, 9, 10, 12]] # initialize the array elements.
print(“Before Deleting the array elements: “)
print(arr1) # print the arr1 elements.
del(arr1[0][2]) # delete the particular element of the array.
del(arr1[1]) # delete the index 1 of the 2-D array.
print(“After Deleting the array elements “)
for i in arr1: # Outer loop
for j in i: # inner loop
print(j, end = ” “) # print inserted elements.
print()
Output:
A len() function is used to get the length of a two-dimensional array. In other words, we can say that a len() function determines the total index available in 2-dimensional arrays.
Let’s understand the len() function to get the size of a 2-dimensional array in Python.
Size.py
array_size = [[1, 3, 2],[2,5,7,9], [2,4,5,6]] # It has 3 index
print(“The size of two dimensional array is : “)
print(len(array_size)) # it returns 3
array_def = [[1, 3, 2], [2, 4, 5, 6]] # It has 2 index
print(“The size of two dimensional array is : “)
print(len(array_def)) # it returns 2
Output:
Write a program to print the sum of the 2-dimensional arrays in Python.
Matrix.py
def two_d_matrix(m, n): # define the function
Outp = [] # initially output matrix is empty
for i in range(m): # iterate to the end of rows
row = []
for j in range(n): # j iterate to the end of column
num = int(input(f “Enter the matrix [0][j]”))
row.append(num) # add the user element to the end of the row
Outp.append(row) # append the row to the output matrix
return Outp
def sum(A, B): # define sum() function to add the matrix.
output = [] # initially, it is empty.
print(“Sum of the matrix is :”)
for i in range(len(A)): # no. of rows
row = []
for j in range(len(A[0])): # no. of columns
row.append(A[i][j] + B[i][j]) # add matrix A and B
output.append(row)
return output # return the sum of both matrix
m = int(input(“Enter the value of m or Rown”)) # take the rows
n = int(input(“Enter the value of n or columnsn”)) # take the columns
print(“Enter the First matrix “) # print the first matrix
A = two_d_matrix(m, n) # call the matrix function
print(“display the first (A) matrix”)
print(A) # print the matrix
print(“Enter the Second (B) matrix “)
B = two_d_matrix(m, n) # call the matrix function
print(“display the Second (B) matrix”)
print(B) # print the B matrix
s= sum(A, B) # call the sum function
print(s) # print the sum of A and B matrix.
Output:
Next TopicPython Memory Management
Reply
9
0
Chia sẻ
– Một số Keywords tìm kiếm nhiều : ” Review Python print 2d list as table tiên tiến và phát triển nhất , Share Link Tải Python print 2d list as table “.
You trọn vẹn có thể để lại Comment nếu gặp yếu tố chưa hiểu nhé.
#Python #print #list #table Python print 2d list as table