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

如何将列表中[blank, 运算符, 数值]转换为对应正负数值元素?

列表模式替换实现方案

核心思路

遍历列表,识别[blank, 运算符, 数字]的连续三元组:

  • 若运算符为subtract,替换为[-数字]
  • 若运算符为add,替换为[数字]
    替换时直接移除原三元组,插入目标数值即可。

Python 实现代码

def transform_list(input_list):
    i = 0
    while i < len(input_list):
        # 检查是否满足三元组条件
        if (i + 2 < len(input_list) 
            and input_list[i] == 'blank' 
            and input_list[i+1] in ['add', 'subtract']):
            op = input_list[i+1]
            num = input_list[i+2]
            # 生成替换值
            replacement = -num if op == 'subtract' else num
            # 替换原三元组为单个值
            del input_list[i:i+3]
            input_list.insert(i, replacement)
            # 替换后索引+1,继续遍历后续元素
            i += 1
        else:
            i += 1
    return input_list

# 测试示例
original_list = [4097, 'add', 1, 'divide', 'blank', 'subtract', 3, 'floor', 1, 'add', 2, 'multiply', 8]
result = transform_list(original_list)
print(result)
# 输出: [4097, 'add', 1, 'divide', -3, 'floor', 1, 'add', 2, 'multiply', 8]

逻辑说明

  1. 用while循环而非for循环,避免列表长度动态变化导致的遍历遗漏
  2. 每次检查当前索引是否存在连续三个元素,且第一个是blank、第二个是目标运算符
  3. 根据运算符计算替换的正负数值,删除原三元组后插入新值
  4. 替换完成后索引递增1,跳过已处理的新元素,继续遍历剩余内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 10:59:56