I have two lists a
and b
:
a = [3, 6, 8, 65, 3]
b = [34, 2, 5, 3, 5]
c gets [3/34, 6/2, 8/5, 65/3, 3/5]
The built-in map() function makes short work of these kinds of problems:
>>> from operator import truediv
>>> a=[3,6,8,65,3]
>>> b=[34,2,5,3,5]
>>> map(truediv, a, b)
[0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6]
Use zip
and a list comprehension:
>>> a = [3,6,8,65,3]
>>> b = [34,2,5,3,5]
>>> [(x*1.0)/y for x, y in zip(a, b)]
[0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6]
You can use the following code:
a = [3, 6, 8, 65, 3]
b = [34, 2, 5, 3, 5]
c = [float(x)/y for x,y in zip(a,b)]
print(c)
You can do this using list comprehension (element by element):
div = [ai/bi for ai,bi in zip(a,b)]
Note that if you want float division, you need to specify this (or make the original values floats):
fdiv = [float(ai)/bi for ai,bi in zip(a,b)]
>>> from __future__ import division # floating point division in Py2x
>>> a=[3,6,8,65,3]
>>> b=[34,2,5,3,5]
>>> [x/y for x, y in zip(a, b)]
[0.08823529411764706, 3.0, 1.6, 21.666666666666668, 0.6]
Or in numpy
you can do a/b
>>> import numpy as np
>>> a=np.array([3,6,8,65,3], dtype=np.float)
>>> b=np.array([34,2,5,3,5], dtype=np.float)
>>> a/b
array([ 0.08823529, 3. , 1.6 , 21.66666667, 0.6 ])
Using numpy.divide
c=np.divide(a,b)