简体   繁体   English

如何将字符串列表转换为sympy变量?

[英]How can I convert a list of strings into sympy variables?

I have a list of strings, eg, var = ['x', 'y', 'z'] . 我有一个字符串列表,例如, var = ['x', 'y', 'z'] I want to use these strings as sympy 'symbols'. 我想将这些字符串用作同情“符号”。 I am trying to do this: 我想这样做:

for i in var:
    i = symbols('i')

it's not working of course. 它当然不起作用。 Can someone help me with this? 有人可以帮我弄这个吗?

Several issues: 几个问题:

  1. The input string is never mutated by a call to sympy.symbols . 调用sympy.symbols ,输入字符串永远不会发生变异。
  2. You need to call symbols with every element of var as an argument, you hardcoded a call with the string argument 'i' . 您需要使用var每个元素作为参数调用symbols ,并使用字符串参数'i'对调用进行硬编码。
  3. The assignment to i inside the loop body is pointless because in the next iteration the name i will be reassigned to the next element from var (which you don't even use). 在循环体内对i的赋值是没有意义的,因为在下一次迭代中,名称i将被重新分配给var的下一个元素(您甚至不使用它)。

So in summary, you need to call symbols with every element of var and store the return values somewhere. 总而言之,您需要使用var每个元素调用symbols并将返回值存储在某处。

>>> import sympy
>>> var_as_strings = ['x', 'y', 'z']
>>> var_as_symbol_objects = [sympy.symbols(v) for v  in var_as_strings]
>>> var_as_symbol_objects
[x, y, z]
>>> type(var_as_symbol_objects[0])
<class 'sympy.core.symbol.Symbol'>

(I used overly verbose variable names to be make the example self-documenting.) (我使用了过于冗长的变量名来使示例自我记录。)

The reason what you did did not work is because you tried to assign a symbol to a string which can't be changed (eg 'a' = 1 will fail for the same reason). 您所做的不起作用的原因是因为您尝试将符号分配给无法更改的字符串(例如,'a'= 1将因同样的原因而失败)。

If you are working interactively and want variables with the same name as the symbols you can write 如果您正在以交互方式工作,并且希望变量与您可以编写的符号同名

>>> var(','.join(variables)) # variables = ['x', 'y', 'z']
(x, y, z)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM