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,)]]

结论

使用列表推导式的优点在于,它允许人们编写几行代码,这些代码更容易理解,并且更容易迭代到列表的特定元素中。为了转换为自定义元组矩阵,我们看到上面讨论了各种方法。在现实生活中,矩阵用于表示统计数据,例如婴儿死亡率、人口等。

更新于: 2023年8月14日

371 次查看

开启你的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.