Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python filter and list and apply "filtered indices" to another list [duplicate]

Tags:

python

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.

like image 588
AJW Avatar asked Nov 15 '12 12:11

AJW


3 Answers

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).

like image 105
Gareth Latty Avatar answered Sep 22 '22 12:09

Gareth Latty


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]
like image 39
Aesthete Avatar answered Sep 19 '22 12:09

Aesthete


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']
like image 21
moooeeeep Avatar answered Sep 19 '22 12:09

moooeeeep