Reputation: 777
I would like to divide list items inside two lists.
a = [[1, 0, 2], [0, 0, 0], [1], [1]]
b = [[5, 6, 4], [6, 6, 6], [3], [3]]
How can I divide a by b to obtain this output:
c = [[0.2, 0, 0.5], [0, 0, 0], [0.333], [0.333]]
Can anyone help me?
Upvotes: 3
Views: 166
Reputation: 101919
Zip the two lists and use a list comprehension:
from __future__ import division # in python2 only
result = [[x/y for x,y in zip(xs, ys)] for xs, ys in zip(a, b)]
Sample run:
In [1]: a = [[1, 0, 2], [0, 0, 0], [1], [1]]
...: b = [[5, 6, 4], [6, 6, 6], [3], [3]]
...:
In [2]: result = [[x/y for x,y in zip(xs, ys)] for xs, ys in zip(a, b)]
In [3]: result
Out[3]: [[0.2, 0.0, 0.5], [0.0, 0.0, 0.0], [0.3333333333333333], [0.3333333333333333]]
Upvotes: 8
Reputation: 304137
from __future__ import division # for Python2
[[x / y for x, y in zip(*item)] for item in zip(a, b)]
Upvotes: 2
Reputation: 76297
Using itertools.izip
(Python2.7):
import itertools
[[float(aaa) / bbb for (aaa, bbb) in itertools.izip(aa, bb)] \
for (aa, bb) in itertools.izip(a, b)]
Upvotes: 5