Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter a list in Python, then unfilter it

Tags:

python

I have a list of items in Python (v2.7 but a v2/v3 compatible solution would be nice), e.g.:

a = [1,6,5,None,5,None,None,1]

I'd like to filter out the None values, and then do something with the resulting list, e.g.:

b = [x for x in a if x is not None]
c = f(b)

Then I'd like to put the None values back in their original indices:

d = # ??? should give me [c[0],c[1],c[2],None,c[3],None,None,c[4]]

I need to pass the entire filtered list to the function f() at once. I'm wondering if there's an elegant way to do this since all of my solutions so far have been messy. Here's the cleanest one I have so far:

d = c
for i in range(len(a)):
    if not a[i]:
        d.insert(i, None)

EDIT: Fixing typo in list comprehension.

like image 280
nonagon Avatar asked Dec 15 '22 22:12

nonagon


1 Answers

Here's a simple solution that seems to do the trick:

>>> a = [1,6,5,None,5,None,None,1]
>>> b = [x for x in a if x is not None]
>>> c = [2,12,10,10,2]  # just an example
>>> 
>>> v = iter(c)
>>> [None if x is None else next(v) for x in a]
[2, 12, 10, None, 10, None, None, 2]
like image 199
arshajii Avatar answered Dec 17 '22 13:12

arshajii