파이썬 2D 배열
배열 연속된 메모리 공간에 동일한 데이터 유형의 모든 요소를 포함하는 선형 데이터 구조의 모음입니다. 이는 동일한 데이터 유형을 가진 특정 수의 요소를 보유하는 컨테이너와 같습니다. 배열의 인덱스는 0부터 시작하므로 프로그래머는 쉽게 각 요소의 위치를 파악하고 배열에 대한 다양한 작업을 수행할 수 있습니다. 이번 섹션에서는 Python의 2D(2차원) 배열에 대해 알아봅니다.
2차원 배열(2D 배열)
2D 배열 행과 열과 같은 행렬 형태로 표현할 수 있는 배열의 배열입니다. 이 배열에서 데이터 요소의 위치는 단일 인덱스 대신 두 개의 인덱스로 정의됩니다.
통사론
Array_name = [rows][columns] # declaration of 2D array Arr-name = [ [m1, m2, m3, … . m<sub>n</sub>], [n1, n2, n3, … .. n<sub>n</sub>] ]
어디 중 행이고 N 테이블의 열입니다.
2차원 배열에 액세스
~ 안에 파이썬 , 두 개의 인덱스를 사용하여 2차원 배열의 요소에 액세스할 수 있습니다. 첫 번째 인덱스는 목록의 인덱싱을 나타내고 두 번째 인덱스는 요소의 위치를 나타냅니다. 배열 이름으로 하나의 인덱스만 정의하면 배열에 저장된 2차원의 모든 요소를 반환합니다.
이해하기 쉽게 간단한 프로그램을 만들어 보겠습니다. 2D Python의 (2차원) 배열.
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.
산출:
위의 예에서는 정의된 인덱스의 전체 행을 인쇄하는 2D 배열에 매개변수로 1, 0, 2를 전달했습니다. 그리고 우리도 합격했어요 학생_dt[3][4] 3을 나타내는 것 rd 인덱스와 4 일 특정 요소를 인쇄하기 위한 요소의 2차원 배열 위치입니다.
2D(2차원)에서 요소 탐색
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()
산출:
2D(2차원) 배열에 요소 삽입
다음을 사용하여 2차원 배열에 요소를 삽입할 수 있습니다. 끼워 넣다() 삽입할 요소의 인덱스 번호와 위치를 지정하는 함수입니다.
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()
산출:
2 -D(2차원) 배열의 요소 업데이트
2D 배열에서는 배열의 기존 값을 새 값으로 업데이트할 수 있습니다. 이 방법에서는 배열의 전체 인덱스뿐만 아니라 특정 값도 변경할 수 있습니다. 아래와 같이 2차원 배열의 예를 들어 이해해 봅시다.
Python에서 2D 배열의 기존 값을 업데이트하는 프로그램을 만듭니다.
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()
산출:
Python의 2D(2차원) 배열에서 값 삭제
2차원 배열에서는 다음을 사용하여 배열의 특정 요소나 전체 인덱스를 제거할 수 있습니다. ()의 파이썬에서 함수. 요소를 삭제하는 예를 살펴보겠습니다.
삭제.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()
산출:
2D 배열의 크기
ㅏ 오직 () 함수는 2차원 배열의 길이를 구하는 데 사용됩니다. 즉, 우리는 다음과 같이 말할 수 있습니다. 오직 () 함수는 2차원 배열에서 사용할 수 있는 전체 인덱스를 결정합니다.
Python에서 2차원 배열의 크기를 구하는 len() 함수를 이해해 보겠습니다.
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
산출:
Python에서 2차원 배열의 합을 출력하는 프로그램을 작성하세요.
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 Row
')) # take the rows n = int(input('Enter the value of n or columns
')) # 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. 산출: