Filter a list in Python, then filter it

I have a list of elements in Python (v2.7, but a v2 / v3 compatible solution would be nice), for example:

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

I would like to filter out the None values ​​and then do something with the resulting list, for example:

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

Then I would like to return None values ​​to their original indexes:

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 f () function right away. I am wondering if there is an elegant way to do this, since all my decisions have so far been dirty. Here is the cleanest I have so far:

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

EDIT: typo correction in list comprehension.

+4
source share
4 answers

Here is 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]
+8
source
a = [1,6,5,None,5,None,None,1]
b = [x for x in a if a is not None]
c = f(b)
d = [x if x is None else c.pop(0) for x in a]
+2
source
j = 0
d = []
for x in a:
    if x is None:
        d.append(None)
    else:
        d.append(c[j])
        j=j+1
+1

, None go:

>>> def f(seq):
...     return [x+x for x in seq]
>>> a = [1,6,5,None,5,None,None,1]
>>> indices, filtered = zip(*[(i, v) for i,v in enumerate(a) if v is not None])
>>> indices
(0, 1, 2, 4, 7)

-:

>>> filtered
(1, 6, 5, 5, 1)
>>> mapped = f(filtered)
>>> mapped
[2, 12, 10, 10, 2]

"" :

>>> unfiltered = dict(zip(indices, mapped))
>>> unfiltered
{0: 2, 1: 12, 2: 10, 4: 10, 7: 2}

, :

>>> result = [unfiltered.get(i) for i in range(len(a))]
>>> result
[2, 12, 10, None, 10, None, None, 2]
+1
source

Source: https://habr.com/ru/post/1542108/


All Articles