【问题标题】:Handle Python reserved words in a sympy parse_expr?在 sympy parse_expr 中处理 Python 保留字?
【发布时间】:2021-02-03 15:22:03
【问题描述】:

如果我解析包含lambda 的表达式,即使Symbol("lambda") 有效,我也会收到错误:

>>> sympy.Symbol("lambda")
lambda
>>> sympy.parse_expr("1 + lambda")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "xxx/lib/python3.7/site-packages/sympy/parsing/sympy_parser.py", line 1008, in parse_expr
    return eval_expr(code, local_dict, global_dict)
  File "xxx/lib/python3.7/site-packages/sympy/parsing/sympy_parser.py", line 903, in eval_expr
    code, global_dict, local_dict)  # take local objects in preference
  File "<string>", line 1
    Integer (1 )+lambda
                      ^
SyntaxError: invalid syntax
>>> sympy.parse_expr("1 + _lambda")
_lambda + 1

我希望我的代码的用户可以随意命名他们的变量。有办法支持吗?

如果不是,我可以想办法在保留字前面加下划线。

如果这很重要,我正在使用 Sympy 1.6。

【问题讨论】:

标签: python sympy python-exec


【解决方案1】:

sympy 中搜索reserved,我发现了使用lamda 的建议(不带“b”)。 https://docs.sympy.org/latest/tutorial/matrices.html?highlight=reserved

In [146]: lamda = symbols('lamda')

In [147]: from sympy.parsing.sympy_parser import standard_transformations

In [148]: parse_expr("1/2+lamda", transformations=standard_transformations)
Out[148]: λ + 1/2

【讨论】:

  • 啊,很好的发现!在我的搜索中没有出现。我认为我的问题的答案是:没有办法使用lambda,我将不得不禁止我的用户使用这种拼写或实现变量名映射。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多