How to divide list of lists by another list of lists in Python?
<p>I have <code>q = [[7,2,3],[4,5,6]]</code> and <code>r=[[6,1,2],[3,4,5]]</code>. I need to divide q by the corresponding elements in r. (i.e. <code>[[7/6,2/1,3/2],[4/3,5/4,6/5]]</code>)</p>

<p>Output needed B = [[1.16,2,1.5],[1.33,1.25,1.2]]</p>

<p>Code:</p>

<p><code>B= [[float(j)/float(i) for j in q] for i in r]</code>. </p>

<p>However, I keep getting an error : TypeError: float() argument must be a string or a number. I have imported division from future. Any suggestions? </p>

<p>You can do:</p>

<pre><code>&gt;&gt;&gt; out=[]
&gt;&gt;&gt; for s1, s2 in zip(q, r):
...    inner=[]
...    for n, d in zip(s1, s2):
...       inner.append(float(n)/d)
...    out.append(inner)
... 
&gt;&gt;&gt; out
[[1.1666666666666667, 2.0, 1.5], [1.3333333333333333, 1.25, 1.2]]
</code></pre>

<p>Or, use numpy:</p>

<pre><code>&gt;&gt;&gt; q=[[7.,2.,3.],[4.,5.,6.]]
&gt;&gt;&gt; r=[[6.,1.,2.],[3.,4.,5.]]
&gt;&gt;&gt; np.array(q)/np.array(r)
array([[ 1.16666667,  2.        ,  1.5       ],
       [ 1.33333333,  1.25      ,  1.2       ]])
</code></pre>

<p>Or, if you have int literals:</p>

<pre><code>&gt;&gt;&gt; q=[[7,2,3],[4,5,6]]
&gt;&gt;&gt; r=[[6,1,2],[3,4,5]]
&gt;&gt;&gt; np.array(q, dtype=float)/np.array(r)
array([[ 1.16666667,  2.        ,  1.5       ],
       [ 1.33333333,  1.25      ,  1.2       ]])
</code></pre>

python algorithm list floating-point division