Python 中將矩陣轉換為自定義元組矩陣
在 Python 中,元組是四種內建資料型別之一,用於收集資料,這些資料由圓括號 () 表示。元組通常用於將多個專案收集到單個專案中。在 Python 中,我們有一些內建函式,如 map()、tuple() 和 lambda,可用於將矩陣轉換為自定義元組矩陣。自定義元組矩陣由元組的子類定義,該子類具有元素,並用逗號分隔以建立子列表(列表表示矩陣)。
讓我們來看一個例子
原始矩陣
[ [11, 21, 31],
[41, 51, 61],
[71, 81, 91] ]
轉換為自定義元組矩陣後:(最終結果)
[[(11,), (21,), (31)], [(41), (51), (61)], [(71), (81), (91)]]
語法
以下語法在示例中使用 -
tuple()
這是 Python 中一個內建函式,可用於建立元組,即 ()。
map()
map 函式允許基於列表、元組等迭代元素以返回特定結果。
lambda
lambda 函式用於表示內聯的小函式。將 lambda 與 map() 函式一起使用是迭代列表、元組等的一種常見做法。
示例 1:使用巢狀列表推導式
在以下示例中,程式使用巢狀列表,該列表由列表中的列表定義。使用 for 迴圈,它將遍歷矩陣列表並將矩陣轉換為自定義元組矩陣。
def matrix_to_custom_tuple(matrix): c_tuple_matrix = [[(value,) for value in row] for row in matrix] return c_tuple_matrix # Taking sublist as an input matrix = [[11, 92, 34], [14, 15, 16], [74, 89, 99]] result = matrix_to_custom_tuple(matrix) print(result)
輸出
[[(11,), (92,), (34,)], [(14,), (15,), (16,)], [(74,), (89,), (99,)]]
示例 2:使用巢狀 for 迴圈
在以下示例中,程式使用巢狀 for 迴圈,這意味著迴圈巢狀在另一個迴圈中,並且它迭代列表的每個元素。使用 append 它接受引數來設定元組,並且將建立此自定義元組矩陣。
def matrix_to_custom_tuple(matrix): cus_tuple_matrix = [] for row in matrix: cus_tuple_row = [] for value in row: cus_tuple_row.append((value,)) cus_tuple_matrix.append(cus_tuple_row) return cus_tuple_matrix # Taking of input matrix inp_matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] answer = matrix_to_custom_tuple(inp_matrix) print("Matrix into Custom Tuple Matrix:\n",answer)
輸出
Matrix into Custom Tuple Matrix: [[(1,), (2,), (3,)], [(4,), (5,), (6,)], [(7,), (8,), (9,)]]
示例 3:使用 map() 和 lambda 函式
在以下示例中,程式使用 Python 中的一些內建函式,如 list()、map() 和 lambda,將矩陣轉換為自定義元組矩陣。
def matrix_to_custom_tuple(matrix): custom_tuple_matrix = list(map(lambda row: list(map(lambda value: (value,), row)), matrix)) return custom_tuple_matrix matrix = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] result = matrix_to_custom_tuple(matrix) print(result)
輸出
[[('A',), ('B',), ('C',)], [('D',), ('E',), ('F',)], [('G',), ('H',), ('I',)]]
示例 4:使用帶有 tuple() 的列表推導式
在以下示例中,程式使用列表推導式定義各種內建函式,如 list()、map()、lambda 和 tuple(),並使用 for 迴圈遍歷矩陣列表。
def matrix_to_custom_tuple(matrix): custom_tuple_matrix = [list(map(lambda value: tuple([value]), row)) for row in matrix] return custom_tuple_matrix # Taking input to store the matrix using sublist of list matx = [[1, 2, 3], [4, 5, 6, 7, 8], [7, 8, 9],[10, 11, 12, 13]] result = matrix_to_custom_tuple(matx) print("Convert the Matrix into Custom Tuple Matrix:\n",result)
輸出
Convert the Matrix into Custom Tuple Matrix: [[(1,), (2,), (3,)], [(4,), (5,), (6,), (7,), (8,)], [(7,), (8,), (9,)], [(10,), (11,), (12,), (13,)]]
結論
使用列表推導式的優點在於,它允許人們編寫幾行程式碼,這些程式碼更容易理解,並且更容易迭代到列表的特定元素中。為了轉換為自定義元組矩陣,我們看到上面討論了各種方法。在現實生活中,矩陣用於表示統計資料,例如嬰兒死亡率、人口等。