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

如何在Python中利用数组数据对字符串执行变量替换?

线性规划Z函数变量替换问题求解

输入数据

示例M×N矩阵与目标函数:

# 示例输入M×N矩阵,本质为由子列表组成的列表
new_matrix_aux = [['X', 'B', 'X1', 'X2', 'X3', 'U1', 'L1', 'L2'], 
                  ['U1', 12,  3.0,  2.0, -1.0,  1.0,    0,    0], 
                  ['L1', 12,  2.0,  3.0,    0,    0,  1.0,    0], 
                  ['L2',  2, -2.0,  1.0,    0,    0,    0,  1.0]]

z_function = "Z = 1 * X1 + 4 * X2 + 0 * X3 + M * U1 + M * L1 + M * L2"

现有错误代码

以下代码因替换逻辑错误,无法得到正确结果:

variables = new_matrix_aux[0][1:]  # 从数组第一行获取变量
replacements = {var: 0 for var in variables}  # 初始化所有变量替换值为0

# 在Z函数中执行替换
for col in range(1, len(new_matrix_aux[0])):
    column_name = new_matrix_aux[0][col]
    for row in range(1, len(new_matrix_aux)):
        variable = new_matrix_aux[row][0]
        value = new_matrix_aux[row][col]
        replacements[variable] = value

    z_function = z_function.replace(column_name, str(replacements[column_name]))

    print(f"Z_{column_name} = {z_function}")

    # 重置替换值为0以进行下一次迭代
    for variable in replacements:
        replacements[variable] = 0

替换规则要求

  1. 第一行(列标题)中未出现在后续子列表开头的变量(如X1、X2、X3),在Z函数中替换为0
  2. 后续子列表开头的变量(如U1、L1、L2),替换为矩阵中对应列的行值
  3. 遍历矩阵所有列(从第二列的B开始),每列替换后输出格式为Z_{列名} = 替换后的表达式

正确实现代码

# 提取行变量:后续行开头的变量(U1、L1、L2)
row_vars = [row[0] for row in new_matrix_aux[1:]]
# 从Z函数中提取所有需要替换的变量
import re
z_expr = z_function.split('=')[1]
z_vars = re.findall(r'\b([A-Za-z0-9]+)\b', z_expr)
z_vars = list(set(z_vars))  # 去重得到独立变量列表

# 遍历所有列(从第二列开始,跳过第一列的X)
for col_idx in range(1, len(new_matrix_aux[0])):
    col_name = new_matrix_aux[0][col_idx]
    # 构建当前列的替换字典
    replace_dict = {}
    for var in z_vars:
        if var in row_vars:
            # 找到变量对应的行索引
            row_idx = row_vars.index(var) + 1  # 加1跳过第一行标题
            replace_dict[var] = str(new_matrix_aux[row_idx][col_idx])
        else:
            replace_dict[var] = '0'
    # 替换Z函数中的变量(正则匹配避免部分替换)
    current_z = z_function
    for var, val in replace_dict.items():
        current_z = re.sub(r'\b' + re.escape(var) + r'\b', val, current_z)
    # 调整输出格式
    current_z = current_z.replace('Z =', f'Z_{col_name} =')
    print(current_z)

预期输出

运行上述代码后,控制台将输出:

Z_B  = 1 * 0 + 4 * 0 + 0 * 0 + M * 12 + M * 12 + M * 2
Z_X1 = 1 * 0 + 4 * 0 + 0 * 0 + M * 3.0 + M * 2.0 + M * -2.0
Z_X2 = 1 * 0 + 4 * 0 + 0 * 0 + M * 2.0 + M * 3.0 + M * 1.0
Z_X3 = 1 * 0 + 4 * 0 + 0 * 0 + M * -1.0 + M * 0 + M * 0
Z_U1 = 1 * 0 + 4 * 0 + 0 * 0 + M * 1.0 + M * 0 + M * 0
Z_L1 = 1 * 0 + 4 * 0 + 0 * 0 + M * 0 + M * 1.0 + M * 0
Z_L2 = 1 * 0 + 4 * 0 + 0 * 0 + M * 0 + M * 0 + M * 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.18 22:39:56