Jido
Jido

Reputation: 3

how to retrieve an integer index from a sympy symbol

I have a list L of sympy symbols defined using the following function : def x(i): return sy.symbols(f'x({i})')

L=[x(10),x(33),....]. Is there away to get the numbers 10,33,... out of the sympy symbols ?

Upvotes: 0

Views: 227

Answers (1)

smichr
smichr

Reputation: 19115

You can parse the numbers out of the symbol name with any python method that you like, e.g.

>>> x = Symbol('x(10)')
>>> int(x.name.split("(")[1].split(")")[0])
10

Of course, the method of parsing will depend on how you hide the number in the symbol name. It might be easier for you to simply work with indexed symbols:

>>> from sympy import IndexedBase
>>> x = IndexedBase('x')
>>> x[1] + x[1]
2*x[1]
>>> x[1].indices
(1,)

Upvotes: 1

Related Questions