SymPy 展开表达式时如何避免按字母顺序排序?
数据小陈
str(sympy.expand(expr)) 不能用来保留元素顺序。expand() 能给出数学上等价的展开式,但 SymPy 的 Add 和 Mul 会按自己的规则组织参数,str() 又按内部顺序打印,所以项的顺序、乘法因子的顺序都可能变。如果顺序有含义,展开过程和最终字符串都得自己控制。
sympy.expand() 会重建表达式。原来 ohio * (idx + sex + recist) 的书写顺序,不会对应展开后 Add/Mul 的 args 顺序。常见输出会变成 idx*ohio + idx + ...,这是 SymPy 打印时排序的结果。打印器的 order 类选项主要管打印排序,没法可靠还原已经被 expand() 改过的表达式树。
题目只涉及 +、* 和非嵌套括号,用 Python 标准库 ast 就够了。思路是把子表达式展开成项列表,每项是一组因子;遇到加法就拼接项列表,遇到乘法就对左右两边的项做笛卡尔积,因子顺序保持从左到右。最后自己拼字符串。
import ast
def expand_keep_order(expr: str) -> str:
tree = ast.parse(expr, mode='eval')
def expand(node):
if isinstance(node, ast.Name):
return [[node.id]]
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
return expand(node.left) + expand(node.right)
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mult):
left_terms = expand(node.left)
right_terms = expand(node.right)
return [left + right for left in left_terms for right in right_terms]
raise ValueError(f'Unsupported node: {ast.dump(node)}')
terms = expand(tree.body)
return ' + '.join('*'.join(term) for term in terms)
examples = [
'idx + ohio * (idx + sex + recist)',
'a * (b + e + c) + d',
'foo + bar + baz * (x)',
]
for expr in examples:
print(expand_keep_order(expr))
输出:
idx + ohio*idx + ohio*sex + ohio*recist
a*b + a*e + a*c + d
foo + bar + baz*x
注意事项:
- 这个实现只处理
+、*、变量名和括号。遇到数字、负号、除法、幂、函数调用等情况,需要在expand()里继续加分支,或者换一个能保留 token 顺序的解析器。 ast.parse要求表达式本身是合法的 Python 表达式。idx、ohio、RECIST这类变量名没问题;如果变量名里有-、空格或中文,就不能直接套这段代码。- 如果还要用 SymPy 验证数学等价,别比较字符串,比较展开后的表达式差:
import sympy
from sympy.parsing.sympy_parser import parse_expr
left = sympy.expand(parse_expr('idx + ohio * (idx + sex + recist)'))
right = sympy.expand(parse_expr('idx + ohio*idx + ohio*sex + ohio*recist'))
assert sympy.simplify(left - right) == 0
- 不建议用
evaluate=False构造Add/Mul来强行控制打印顺序。它可能影响局部 args,但后续化简、打印器和expand()仍可能重排,稳定性不好。
备注:内容仅供参考。
