I want to access the elements of a list
given a condition on another list. Normally, I would do this by using NumPy, but the requirements I have to follow state that I have to stick to Python Standard Library. An example of my problem is the following:
x = [1, 7, 11, 8, 13, 2]
y = [0,3,0,5,2]
#NumPy notation
z = x[y==0]
I have come up with a solution by using a list comprehension:
z = [x[i] for i in xrange(len(y)) if y[i] == 0]
However, it is quite slower in comparison to my implementation in NumPy. Is there any better way to address this?
EDIT: I have not mentioned but my requirements include the use of python 2
You can zip()
the items together:
try:
# iterator zip from Python 3
from future_builtins import zip
except ImportError:
# this *is* Python 3
pass
z = [xval for xval, yval in zip(x, y) if yval == 0]
This also avoids building a list for the zip()
even when using Python 2.
I'd personally use iterators
and zip
(if one list is shorter, it will be quicker)
That way I avoid the double access to elements and I don't have exception if a list is shorter than the other (you should use in xrange(min(len(x),len(y))
)
[a for (a,b) in zip(x,y) if b==0]
Note that zip is iterator for python 3, not for python 2
I haven't benchmarked though
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.