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

如何用Python3过滤含canonical vector的矩阵列(无第三方库)

修正矩阵筛选规范列的代码问题

问题背景

**规范列(canonical column)指包含规范向量(canonical vector)**的列,规范向量的定义是:仅单个元素为1、其余元素均为0的向量。

给定目标矩阵:

matrix = [['X1', 'X2', 'X3', 'X4', 'X5', 'U1', 'U2', 'B'], [2.0, 1.0, -1.0, 0, 0, 1.0, 0, 8], [1.0, 1.0, 0, 1.0, 0, 0, 0, 2], [1.0, 2.0, 0, 0, -1.0, 0, 1.0, 8]]

需要仅保留其中含规范向量的列,预期结果为:

matrix = [['X4', 'U1', 'U2'], [0, 1.0, 0], [1.0, 0, 0], [0, 0, 1.0]]

错误代码及输出

原错误代码:

matrix = [['X1', 'X2', 'X3', 'X4', 'X5', 'U1', 'U2', 'B'], [2.0, 1.0, -1.0, 0, 0, 1.0, 0, 8], [1.0, 1.0, 0, 1.0, 0, 0, 0, 2], [1.0, 2.0, 0, 0, -1.0, 0, 1.0, 8]]

# 获取含canonical vector的列索引(仅单个位置为1.0)
columnas_canonicas = [i for i, columna in enumerate(zip(*matrix[1:])) if sum(1 for elemento in columna if elemento == 1.0) == 1]

# 过滤含canonical vector的列
matrix_aux = [[fila[0]] + [fila[i+1] for i in columnas_canonicas] for fila in matrix]

print(matrix_aux) # 输出矩阵

错误输出:

[['X1', 'X5', 'U2', 'B'], [2.0, 0, 0, 8], [1.0, 0, 0, 2], [1.0, -1.0, 1.0, 8]]

输出中没有任何符合要求的规范列。

问题分析

  • 仅判断列中1.0的数量为1,但未验证其余元素是否全为0,导致包含负数、非零正数的列被误选。
  • 索引逻辑错误:原代码错误保留了表头行的第一个元素X1,同时对列索引的映射处理混乱,导致选到不符合要求的列。

修正后的代码

matrix = [['X1', 'X2', 'X3', 'X4', 'X5', 'U1', 'U2', 'B'], [2.0, 1.0, -1.0, 0, 0, 1.0, 0, 8], [1.0, 1.0, 0, 1.0, 0, 0, 0, 2], [1.0, 2.0, 0, 0, -1.0, 0, 1.0, 8]]

# 获取符合规范向量的列的原索引
# 规范向量要求:列中恰好有一个1.0,其余元素全为0
canonical_col_indices = []
for col_idx in range(len(matrix[0])):
    # 提取当前列的数值部分(跳过第一行表头)
    col_values = [row[col_idx] for row in matrix[1:]]
    count_ones = sum(1 for val in col_values if val == 1.0)
    # 统计非0非1的元素数量,确保其余都是0
    count_invalid = sum(1 for val in col_values if val not in (0, 1.0))
    if count_ones == 1 and count_invalid == 0:
        canonical_col_indices.append(col_idx)

# 过滤矩阵,只保留符合条件的列
filtered_matrix = [[row[col_idx] for col_idx in canonical_col_indices] for row in matrix]

print(filtered_matrix)

输出结果

[['X4', 'U1', 'U2'], [0, 1.0, 0], [1.0, 0, 0], [0, 0, 1.0]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:53:21