Possible Duplicate:
Python: Elegant and efficient ways to mask a list
I have two equal sized lists, something like:
a=["alpha","beta","kappa","gamma","lambda"]
b=[1,2,None,3,4,5]
What I would like to do is identify and delete the none element in list [b] and then remove the corresponding element in list [a]. Here, for example, I would like to delete none and "kappa".
I am aware of:
filter(bool,b)
which would remove the None elements from [b], but, how do I go about deleting the corresponding entry in list[a]?
I tried zip, something like (the idea was to pack and unpack):
a=["a","b","c","d","e"]
b=[1,2,None,3,4]
c=zip(a,b)
d=filter(bool,c)
..but this does not work. [d] still has the none elements.
I would appreciate any pythonic way to achieve this.
This can be done neatly with itertools.compress()
and a list comprehension:
>>> a=["a", "b", "c", "d", "e"]
>>> b=[1, 2, None, 3, 4]
>>> selectors = [x is not None for x in b]
>>> list(itertools.compress(a, selectors))
['a', 'b', 'd', 'e']
>>> list(itertools.compress(b, selectors))
[1, 2, 3, 4]
This method means you only generate the selectors once (and itertools.compress()
should be nice and fast).
a = [a[i] for i,v in enumerate(a) if b[i] is not None]
b = [x for x in b if x is not None]
Just use a list comprehension and add that condition to the generator expression:
>>> a=["a","b","c","d","e"]
>>> b=[1,2,None,3,4]
>>> [x for x in zip(a,b) if x[1] is not None]
[('a', 1), ('b', 2), ('d', 3), ('e', 4)]
>>> [x for x,m in zip(a,b) if m is not None]
['a', 'b', 'd', 'e']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With