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

Python实现函数复合的字典表示:如何补全缺失的除法运算符?

修复函数表达式转字典时缺失运算符键的问题

需求是将类似 NUM(CEIL(NUM(MONTH(DATA))/3), 00) 的函数表达式转换为嵌套字典,期望输出包含除法运算符 / 作为键:

{'NUM': {'CEIL': {'/': {'NUM': {'MONTH': {'DATA': None}}, '3': None}}, '00': None}}

但当前实现的代码输出缺失了 / 键,输出结果为:

{'NUM': {'CEIL': {'NUM': {'MONTH': {'DATA': None}}, '3': None}, '00': None}}

问题原因

原代码处理 /、* 这类二元运算符时逻辑有误:当检测到运算符时,仅做了清空key的操作,没有将运算符作为键构建对应的字典结构,导致运算符被直接忽略。

修改后的代码

def text_formula_to_dict(text_formula):
    stack = []
    current_dict = {}
    key = ''
    special_chars = set(['(', ')', ',', '/', '*'])

    for char in text_formula:
        if char == '(':
            if key:
                # 遇到左括号,将当前字典和函数名入栈,开始构建新的子字典
                stack.append((current_dict, key.strip()))
                current_dict = {}
                key = ''
        elif char == ')':
            if key:
                current_dict[key.strip()] = None
                key = ''
            # 遇到右括号,将当前子字典挂载到父字典的对应键下
            if stack:
                parent_dict, parent_key = stack.pop()
                parent_dict[parent_key] = current_dict
                current_dict = parent_dict
        elif char == ',':
            if key:
                current_dict[key.strip()] = None
                key = ''
        elif char in ['/', '*']:
            # 处理二元运算符:先把当前已解析的内容作为左操作数
            if key:
                current_dict[key.strip()] = None
                key = ''
            # 保存当前左操作数字典,以运算符为键创建新字典,入栈等待右操作数
            stack.append((current_dict, char))
            new_dict = {}
            # 取出左操作数的键值对,移入新字典
            left_key, left_val = next(iter(current_dict.items()))
            new_dict[left_key] = left_val
            current_dict = new_dict
        elif char in special_chars:
            # 处理其他未单独匹配的特殊字符
            if key:
                current_dict[key.strip()] = None
                key = ''
            key += char
        else:
            key += char
    if key:
        current_dict[key.strip()] = None

    return current_dict

修改说明

  1. 单独拆分了 / 和 * 的处理逻辑,不再混在通用特殊字符处理流程中
  2. 遇到运算符时,先将当前已解析的内容作为左操作数存入新字典,然后将运算符和新字典入栈
  3. 后续解析右操作数时,会直接挂载到这个以运算符为键的字典下,最终保留运算符的结构

测试验证

调用函数处理示例表达式:

print(text_formula_to_dict("NUM(CEIL(NUM(MONTH(DATA))/3), 00)"))

输出结果与期望一致:

{'NUM': {'CEIL': {'/': {'NUM': {'MONTH': {'DATA': None}}, '3': None}}, '00': None}}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 00:32:41