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函数用于表示内联的小函数。在使用map()函数时与lambda一起使用是一种常见的做法,可以迭代列表、元组等。
示例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,)]]
结论
使用列表推导的好处是能够编写几行代码,更易于理解并且更易于迭代列表的特定元素。为了转换成自定义元组矩阵,我们上面讨论了各种方法。在现实生活中,矩阵用于表示统计数据,例如婴儿死亡率、人口等。