h[1] >>> from sympy.tensor import * h[1] >>> M=Indexed('M') h[1] >>> var('i j k', integer=1) (i, j, k) h[2] >>> eq=1+2*M(i,1)+3*j+4*M(i,2); eq 1 + 2*M(i, 1) + 3*j + 4*M(i, 2) h[3] >>> for a in eq.as_Add(): ... ie = [] ... co = [] ... for m in a.as_Mul(): ... if isinstance(m, IndexedElement): ... ie.append(m) ... else: ... co.append(m) ... if ie: ... print Mul(*co), Mul(*ie) ... 4 M(i, 2) 2 M(i, 1) h[3] >>>
If there's always only going to be one IndexedElement per term then you could find them all with atoms and then find their coefficients with coeff. But if you are worried about efficiency then you could just check for an IndexedElement atom in a given term and find the coeff of it when found: h[3] >>> for a in eq.as_Add(): ... ie = a.atoms(IndexedElement) ... if ie: ... assert len(ie) == 1 ... ie = ie.pop() ... print a.coeff(ie), ie ... 4 M(i, 2) 2 M(i, 1) If you need to know which argument it was then you can use the enumerate to keep track of which "a" it was that had that term: h[3] >>> for i, a in enumerate(eq.as_Add()): ... ie = a.atoms(IndexedElement) ... if ie: ... assert len(ie) == 1 ... ie = ie.pop() ... print i, a.coeff(ie), ie ... 2 4 M(i, 2) 3 2 M(i, 1) h[3] >>> print eq.args (1, 3*j, 4*M(i, 2), 2*M(i, 1)) -- You received this message because you are subscribed to the Google Groups "sympy" group. To post to this group, send email to sy...@googlegroups.com. To unsubscribe from this group, send email to sympy+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/sympy?hl=en.