1

I have q = [[7,2,3],[4,5,6]] and r=[[6,1,2],[3,4,5]]. I need to divide q by the corresponding elements in r. (i.e. [[7/6,2/1,3/2],[4/3,5/4,6/5]])

Output needed B = [[1.16,2,1.5],[1.33,1.25,1.2]]

Code:

B= [[float(j)/float(i) for j in q] for i in r].

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

3
  • 2
    You need to iterate over the values in the sublists, not the sublists themselves. Right now you're trying to convert lists into floats... Commented Oct 11, 2016 at 4:41
  • 3
    numpy will do that for you! Commented Oct 11, 2016 at 4:42
  • I am not comfortable using numphy, Any suggestions for this code? Commented Oct 11, 2016 at 4:43

2 Answers 2

8

Use zip for bring together the sublists pairwise and then use it again to bring together the corresponding numerators and denominators:

>>> q = [[7,2,3],[4,5,6]]
>>> r = [[6,1,2],[3,4,5]]
>>> [[n/d for n, d in zip(subq, subr)] for subq, subr in zip(q, r)]
[[1.1666666666666667, 2.0, 1.5], [1.3333333333333333, 1.25, 1.2]]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. How does this work for an integer divided by one element in a list of lists? I tried doing it in this (stackoverflow.com/q/39969884/6820344) question I posted. Under "Failed Output", you can see that it does not allow one to do this type of division.
If Python 2, you need [[float(n)/d for n, d in zip(subq, subr)] for subq, subr in zip(q, r)]
For Python 2, add from __future__ import division.
2

You can do:

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

Or, use numpy:

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

Or, if you have int literals:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.