Collecting like term of an expression in Sympy
<p>I am currently dealing with functions of more than one variable and need to collect like terms in an attempt to simplify an expression.</p>

<p>Say the expression is written as follows:</p>

<pre><code>x = sympy.Symbol('x')
y = sympy.Symbol('y')
k = sympy.Symbol('k')
a = sympy.Symbol('a')

z = k*(y**2*(a + x) + (a + x)**3/3) - k((2*k*y*(a + x)*(n - 1)*(-k*(y**2*(-a + x) + (-a + x)**3/3) + k*(y**2*(a + x) + (a + x)**3/3)) + y)**2*(-a + k*(n - 1)*(y**2 + (a + x)**2)*(-k*(y**2*(-a + x)))))
zEx = z.expand()
print type(z)
print type(zEx)
</code></pre>

<p>EDIT: Formatting to add clarity and changed  the expression z to make the problem easier to understand.</p>

<p>Say <code>z</code> contains so many terms, that sifting through them by eye. and selecting the appropriate terms, would take an unsatisfactory amount of time. </p>

<p>I want to collect all of the terms which are <strong>ONLY</strong> a multiple of a**1. I do not care for quadratic or higher powers of a, and I do not care for terms which do not contain a. </p>

<p>The type of <code>z</code> and <code>zEx</code> return the following:</p>

<pre><code>print type(z)
print type(zEx)
&gt;&gt;&gt;
&lt;class 'sympy.core.add.Add'&gt;
&lt;class 'sympy.core.mul.Mul'&gt;
</code></pre>

<p>Does anyone know how I can collect the terms which are a multiple of <code>a</code> , not a^0 or a^2?</p>

<p>tl'dr </p>

<p>Where z(x,y) with constants a and k described by <code>z</code> and <code>zEx</code> and their type(): How can one remove all non-<code>a</code> terms from <code>z</code> AND remove all quadratic or higher terms of <code>a</code> from the expression? Such that what is left is <strong>only</strong> the terms which contain a unity power of <code>a</code>.</p>