Biotechgeek Biotechgeek - 1 year ago 70
Python Question

How to divide list of lists by another list of lists in Python?

I have

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

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


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?

Answer Source

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]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download