You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何计算元组型矩阵对应位置的多组合最大值

问题说明

编写Python代码尝试获取元组构成的矩阵的对应位置最大值,原代码如下:

m = int(input("Number of matrices: "))
rows = int(input("Enter the Number of rows : "))
column = int(input("Enter the Number of Columns: "))

p = 0
for i in range(0,m):
    print("Enter the elements of Matrix:")
    matrix_i = [[tuple(map(float, input().split(" "))) for i in range(column)] for i in range(rows)]
    p = p + 1
    print("Matrix no: ", p)
    for n in matrix_i:
        print(n)
        
res = tuple(map(lambda i, j: max(i ,j) , matrix_i, matrix_i))

print(res)

运行代码输入3个2行2列(每个元素为3值元组)的矩阵后,仅输出了最后一个矩阵的两行内容组成的元组,无法得到正确的逐位置最大值,同时需要额外实现:

  • 计算所有两两矩阵组合(1&2、3&2、1&3)的逐位置元组最大值
  • 计算三个矩阵共同的逐位置元组最大值
  • 输出所有组合对应的最大值矩阵

其中三个矩阵共同最大值的预期结果为:

[(7.0, 7.0, 8.0), (6.0, 8.0, 8.0)]
[(9.0, 4.0, 6.0), (9.0, 6.0, 4.0)]
错误原因分析

原代码无法得到正确结果的核心问题有3个:

  • 矩阵存储逻辑错误:循环输入矩阵时反复对matrix_i变量赋值,前两个输入的矩阵会被直接覆盖,计算阶段仅能拿到最后输入的第3个矩阵,完全丢失矩阵1、2的数据
  • 最大值计算逻辑层级错误:原计算逻辑仅在矩阵的「行」层级做比较,没有深入到行内元组的单个元素位置做逐位最大值比对,且传入的两个比对对象都是同一个最后存储的矩阵,本质是把矩阵和自身做行比较
  • 变量命名隐患:列表推导式的两层循环都使用i作为迭代变量名,容易出现变量覆盖导致的非预期逻辑问题
修正实现代码

修正后代码会先存储所有输入的矩阵,再通过通用逐位置最大值计算函数,自动生成所有矩阵组合并计算对应结果:

from itertools import combinations

def get_elementwise_max(*matrices):
    # 校验所有矩阵维度一致
    row_count = len(matrices[0])
    col_count = len(matrices[0][0])
    for mat in matrices:
        assert len(mat) == row_count, "矩阵行数不一致"
        assert len(mat[0]) == col_count, "矩阵列数不一致"
    
    res = []
    # 逐行遍历
    for row_idx in range(row_count):
        current_row = []
        # 逐列遍历
        for col_idx in range(col_count):
            # 收集所有矩阵当前位置的元组,逐位取最大值
            pos_tuples = [mat[row_idx][col_idx] for mat in matrices]
            max_tuple = tuple(max(vals) for vals in zip(*pos_tuples))
            current_row.append(max_tuple)
        res.append(current_row)
    return res

# 输入配置
m = int(input("Number of matrices: "))
rows = int(input("Enter the Number of rows : "))
column = int(input("Enter the Number of Columns: "))

matrices = []
for mat_idx in range(m):
    print(f"Enter the elements of Matrix {mat_idx+1}:")
    current_mat = []
    for _ in range(rows):
        row = []
        for _ in range(column):
            # 每个位置输入3个浮点数组成元组
            ele = tuple(map(float, input().split(" ")))
            row.append(ele)
        current_mat.append(row)
    matrices.append(current_mat)
    print(f"Matrix no: {mat_idx+1}")
    for r in current_mat:
        print(r)

# 计算所有两两组合的最大值
print("\n===== 两两矩阵组合逐位置最大值 =====")
for combo in combinations(range(m), 2):
    print(f"矩阵{combo[0]+1} & 矩阵{combo[1]+1} 最大值:")
    max_mat = get_elementwise_max(matrices[combo[0]], matrices[combo[1]])
    for r in max_mat:
        print(r)

# 计算全部矩阵共同的最大值
print("\n===== 全部矩阵共同逐位置最大值 =====")
all_max_mat = get_elementwise_max(*matrices)
for r in all_max_mat:
    print(r)
结果验证

使用提供的测试输入运行代码,三个矩阵共同计算的输出和预期结果完全一致,所有两两组合的结果也会按相同格式输出。


内容的提问来源于stack exchange,提问作者Mershia Rabuni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 03:30:50