logo

Matriu 2D de Python

Una matriu és una col·lecció d'estructures de dades lineals que contenen tots els elements del mateix tipus de dades en un espai de memòria contigu. És com un contenidor que conté un nombre determinat d'elements que tenen el mateix tipus de dades. L'índex d'una matriu comença a 0 i, per tant, el programador pot obtenir fàcilment la posició de cada element i realitzar diverses operacions a la matriu. En aquesta secció, coneixerem les matrius 2D (bidimensionals) a Python.

Matriu 2D de Python

Matriu bidimensional (matriu 2D)

Una matriu 2D és una matriu de matrius que es poden representar en forma de matriu com files i columnes. En aquesta matriu, la posició dels elements de dades es defineix amb dos índexs en lloc d'un únic índex.

Sintaxi

desinstal·leu angular cli
 Array_name = [rows][columns] # declaration of 2D array Arr-name = [ [m1, m2, m3, &#x2026; . m<sub>n</sub>], [n1, n2, n3, &#x2026; .. n<sub>n</sub>] ] 

On m és la fila i n és la columna de la taula.

Accés a la matriu bidimensional

En Python , podem accedir a elements d'una matriu bidimensional mitjançant dos índexs. El primer índex fa referència a la indexació de la llista i el segon índex fa referència a la posició dels elements. Si definim només un índex amb un nom de matriu, retorna tots els elements de 2 dimensions emmagatzemats a la matriu.

Creem un programa senzill d'entendre 2D matrius (bidimensionals) en 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. 

Sortida:

Matriu 2D de Python

A l'exemple anterior, hem passat 1, 0 i 2 com a paràmetres a la matriu 2D que imprimeix tota la fila de l'índex definit. I també hem passat student_dt[3][4] que representa el 3rdíndex i 4thposició d'una matriu bidimensional d'elements per imprimir un element concret.

Travessant l'element en 2D (bidimensional)

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 = &apos; &apos;) # print the elements print() 

Sortida:

Matriu 2D de Python

Inserir elements en una matriu 2D (bidimensional).

Podem inserir elements en una matriu 2D utilitzant el inserir () funció que especifica el número d'índex i la ubicació de l'element que cal inserir.

La cadena de Java està buida

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(&apos;Before inserting the array elements: &apos;) 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(&apos;After inserting the array elements &apos;) for i in arr1: # Outer loop for j in i: # inner loop print(j, end = &apos; &apos;) # print inserted elements. print() 

Sortida:

Matriu 2D de Python

Actualitzar elements en una matriu 2-D (bidimensional).

En una matriu 2D, el valor existent de la matriu es pot actualitzar amb un valor nou. En aquest mètode, podem canviar el valor particular així com l'índex sencer de la matriu. Anem a entendre amb un exemple de matriu 2D, com es mostra a continuació.

Creeu un programa per actualitzar el valor existent d'una matriu 2D a 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(&apos;Before inserting the array elements: &apos;) 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(&apos;After inserting the array elements &apos;) for i in arr1: # Outer loop for j in i: # inner loop print(j, end = &apos; &apos;) # print inserted elements. print() 

Sortida:

Matriu 2D de Python

Suprimiu valors d'una matriu 2D (bidimensional) a Python

En una matriu 2-D, podem eliminar l'element particular o l'índex sencer de la matriu utilitzant del() funció en Python. Entendrem un exemple per eliminar un 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(&apos;Before Deleting the array elements: &apos;) 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(&apos;After Deleting the array elements &apos;) for i in arr1: # Outer loop for j in i: # inner loop print(j, end = &apos; &apos;) # print inserted elements. print() 

Sortida:

Matriu 2D de Python

Mida d'una matriu 2D

A només La funció () s'utilitza per obtenir la longitud d'una matriu bidimensional. En altres paraules, podem dir que a només La funció () determina l'índex total disponible en matrius bidimensionals.

Entenem la funció len() per obtenir la mida d'una matriu bidimensional a Python.

numera l'alfabet

Size.py

 array_size = [[1, 3, 2],[2,5,7,9], [2,4,5,6]] # It has 3 index print(&apos;The size of two dimensional array is : &apos;) print(len(array_size)) # it returns 3 array_def = [[1, 3, 2], [2, 4, 5, 6]] # It has 2 index print(&apos;The size of two dimensional array is : &apos;) print(len(array_def)) # it returns 2 

Sortida:

Matriu 2D de Python

Escriu un programa per imprimir la suma de les matrius bidimensionals en 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 &apos;Enter the matrix [{0}][{j}]&apos;)) 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(&apos;Sum of the matrix is :&apos;) 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(&apos;Enter the value of m or Row
&apos;)) # take the rows n = int(input(&apos;Enter the value of n or columns
&apos;)) # take the columns print(&apos;Enter the First matrix &apos;) # print the first matrix A = two_d_matrix(m, n) # call the matrix function print(&apos;display the first (A) matrix&apos;) print(A) # print the matrix print(&apos;Enter the Second (B) matrix &apos;) B = two_d_matrix(m, n) # call the matrix function print(&apos;display the Second (B) matrix&apos;) print(B) # print the B matrix s= sum(A, B) # call the sum function print(s) # print the sum of A and B matrix. 

Sortida:

Matriu 2D de Python