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