Python 中二維列表的對角線列印
Python 是一種高階程式語言,也是一種多功能的語言,它最受開發人員的青睞,並且廣泛用於藉助機器學習和資料科學進行資料分析。它提供的用於處理資料的功能非常強大,在本文中,我們將瞭解如何對二維列表進行對角線列印。 這是其中一項基本任務,並且可以透過多種方法有效地實現。
列印二維列表的對角線
在開始列印二維列表的對角線之前,我們需要了解對角線是如何表示的。 對角線由元素組成,指的是從左上角到右下角元素的直線上的這些元素。 對角線元素的基本語法如下所示:
語法
[D1 0 0] [0 D2 0] [0 0 D3]
上面矩陣的對角線為 {D1, D2, D3}。 透過舉例說明主對角線和次對角線的定義是最好的方法:
[D1 0 D2] [0 D3 0] [D4 0 D5]
主對角線元素為 D1、D3、D5
次對角線元素為 D2、D3、D4
方法
方法 1 - 使用函式定義列印主對角線。
方法 2 - 使用函式定義列印次對角線。
方法 1:使用函式定義列印二維列表的對角線(主對角線)的 Python 程式
透過定義函式並滿足行元素等於列元素的條件來列印元素。
演算法
步驟 1 - 定義一個帶有一個引數的函式 diagonal。
步驟 2 - 然後使用 len 函式,我們可以獲取對角矩陣的行和列的長度。
步驟 3 - 使用列表推導式和 for 迴圈,可以遍歷行元素列表,另一個 for 迴圈可以遍歷列元素列表。
步驟 4 - 列印主對角線元素的條件是行元素和列元素相等。
步驟 5 - 用值初始化矩陣元素列表,然後 print 函式將在定義的列表中返回對角線元素。
示例
#Declaring the function with one argument as mat def diag(mat): #To get length using the len function of rows and columns rows = len(mat) cols = len(mat) #To iterate through the row range for a in range(rows): # To iterate through the column range for b in range(cols): #Condition to check whether the row element is equal to the column element if a==b: print(mat[a][b], end="") print() #Declaring the input list of elements mat = [[10, 0, -1], [0, 20, -2], [-3, 0, 30]] #function is called to get the diagonal values diag(mat)
輸出
10 20 30
方法 2:使用迭代方法列印二維列表的對角線(次對角線)的 Python 程式
列印給定列表的對角線,該對角線遵循次對角線,其背後的主要條件是從最後一列到第一列的所有列的行號等於行總數減去元素的當前位置或索引。
演算法
步驟 1 - 定義一個函式,其中一個引數作為矩陣。
步驟 2 - 使用 len 函式獲取行和列的長度。
步驟 3 - for 迴圈將遍歷行和列元素的範圍。
步驟 4 - 需要滿足的條件是,當追加的行元素和列元素必須等於 (n-1) 時。
步驟 5 - print 函式將在每行中返回反對角線元素。
步驟 6 - 矩陣在單獨的列表資料結構中初始化,並呼叫函式列印元素。
示例
#defining the function with one argument def diag(mat): #To get length using the len() function of rows and columns rows = len(mat) cols = len(mat) #To iterate through the row range for a in range(rows): #To iterate through the column range for b in range(cols): #checking the condition to return the antidiagonal matrix if (a == rows - b -1): print(mat[a][b], end=" ") print() #Declaring the input list of elements mat = [[10, 0, -1], [0, 20, -2], [-3, 0, 30]] #function is called to get the diagonal values diag(mat)
輸出
-1 20 -3
結論
Python 透過簡單的概念和易於理解操作背後的概念,使流程變得更加簡單。 給出的方法使用了列印次對角線和主對角線中元素的方法。 透過二維陣列中的迭代方法可以輕鬆地完成列印對角線元素的 Python 程式。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP