Ecanales Ecanales - 2 months ago 11
Python Question

Dividing a list by another with some "0"s in the denominator list

I have the following to divide one list by another (they are vectors):

from operator import truediv
x = [1,0,0,7]
y = [2,3,0,5]
z = map(truediv,x,y)

Is there a way to skip the 0's in the y vector? Hopefully not adding too much iteration. My actual lists are obviously much longer (about 1200 elements each) than this and there's lots of them.


You probably want something like:

from __future__ import division
z = [xx / yy for xx, yy in zip(x, y) if yy]
# or
default = 0  # just a guess...
z = [xx / yy if yy else default for xx, yy in zip(x, y)]

filtering while iterating is one of the things that list-comprehensions do much more expressively than you can get in a more functional style of programming (e.g. using map). There are times when map is more convenient (e.g. when the function being applied is more complex), but for this simple case I'd go with the list-comprehension (or generator expression).