区分具有未知数量变量的 sympy 函数

Differentiating a sympy function with an unknown number of variables

假设我有一个脚本可以创建一个向量 v,其中包含一定数量的元素 x1、x2、x3 等(每个元素都是一个 sympy 符号)。

import sympy as sp

# generated by script, so the number of symbols/length of v is always different:
sp.var("x1,x2,x3,x4,...")
v = sp.Matrix([x1,x2,x3,x4,...])

g = sp.Function("g")

我希望 g 是 x1,x2,x3,... 的函数,所以 g(x1,x2,x3,x4,...) 以便对其求微分。

g.diff(x1) # does not work
g(x1,x2,x3).diff(x1) # works, but the number of variables varies

知道如何解决这个问题吗?

编辑:我应该提到我做了很多研究。我希望我没有遗漏任何明显的东西。

使用 星号表达式

In [13]: g(*v)
Out[13]: g(x1, x2, x3, x4)

In [14]: g(*v).diff(x1)
Out[14]: Derivative(g(x1, x2, x3, x4), x1)