我有代码:

import re
import math
#from sympy import * # breaks?
#x, y, z = symbols('x y z')
#init_printing(use_unicode=True)


def evaluate_expression(expr, variables):
    # Evaluate the expression using eval(), and provide the variables dictionary
    return eval(expr, variables)

def main():
    tools = """
<<<[eval("5"),a_x]>>>
<<<[eval("5+a_x"),ans]>>>
"""

    variables = {}
    lines = tools.strip().split("\n")

    for line in lines:
        # Extract the inner array using regular expression
        match = re.search(r'<<<\[(.*?),(\w+)\]>>>', line)
        if match:
            # Extract expression and variable name
            expr = match.group(1)
            var_name = match.group(2)

            # Evaluate expression
            value = evaluate_expression(expr, variables)

            # Update variables dictionary
            variables[var_name] = value

            # Check if 'ans' is defined
            if 'ans' in variables:
                print("ans =", variables['ans'])
                break

if __name__ == "__main__":
    main()

如果我不导入symy,它运行得很好,但如果我确实导入symy,它就会崩溃,重新搜索不再存在,无论我给变量命名什么.我不明白吗?

推荐答案

sympyre class,当您导入所有*时,您会隐藏re导入.首先导入sympy(或仅导入您实际需要的内容)

from sympy import *
import re

# Output: ans = 10

Python相关问答推荐

从DataFrame.apply创建DataFrame

将轨迹优化问题描述为NLP.如何用Gekko解决这个问题?当前面临异常:@错误:最大方程长度错误

Python Hashicorp Vault库hvac创建新的秘密版本,但从先前版本中删除了密钥

使用SciPy进行曲线匹配未能给出正确的匹配

使用新的类型语法正确注释ParamSecdecorator (3.12)

对某些列的总数进行民意调查,但不单独列出每列

将输入聚合到统一词典中

Odoo 16使用NTFS使字段只读

mypy无法推断类型参数.List和Iterable的区别

使用Python和文件进行模糊输出

Python—转换日期:价目表到新行

为什么常规操作不以其就地对应操作为基础?

替换现有列名中的字符,而不创建新列

Pandas:填充行并删除重复项,但保留不同的值

PYTHON、VLC、RTSP.屏幕截图不起作用

Cython无法识别Numpy类型

如何按row_id/row_number过滤数据帧

统计numpy. ndarray中的项目列表出现次数的最快方法

当我定义一个继承的类时,我可以避免使用`metaclass=`吗?

如何通过特定导入在类中执行Python代码