Reputation: 1473
Given a list A
of bool elements and another list B
with the same length, the goal is to do something essentially
B = [B[i] for i in xrange(len(A)) if A[i]]
However, sometimes B
is not a basic python list; for example, it might be created with manager.list()
, where manager
is an instance of Manager()
from the multiprocessing
module. The above list comprehension will turn it into a plain list, which will lose the desired function (to share data between subprocesses).
What I come up with is something like
def my_filter(A, B):
c = 0
for i in xrange(len(A)):
if not A[i]:
B.pop(i-c)
c = c + 1
So that my_filter(A, B)
will turn B
into its sub-list where the elements of A
are True
.
However, this is a bit "ugly". Is there a more "pythonic" way to do this?
Upvotes: 0
Views: 53
Reputation: 113978
maybe something like this?
B = B.__class__([itemB for itemA,itemB in zip(A,B) if itemA])
or probably better
B[:] = [itemB for itemA,itemB in zip(A,B) if itemA]
Upvotes: 1