在Python中过滤列表,然后对其进行过滤

non*_*gon 4 python

我有一个Python项目列表(v2.7但v2/v3兼容解决方案会很好),例如:

a = [1,6,5,None,5,None,None,1]
Run Code Online (Sandbox Code Playgroud)

我想过滤掉None值,然后对结果列表做一些事情,例如:

b = [x for x in a if x is not None]
c = f(b)
Run Code Online (Sandbox Code Playgroud)

然后我想将None值放回原始索引中:

d = # ??? should give me [c[0],c[1],c[2],None,c[3],None,None,c[4]]
Run Code Online (Sandbox Code Playgroud)

我需要立即将整个过滤列表传递给函数f().我想知道是否有一种优雅的方式来做到这一点,因为到目前为止我所有的解决方案都很混乱.这是我迄今为止最干净的一个:

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

编辑:修复列表理解中的拼写错误.

ars*_*jii 8

这是一个简单的解决方案,似乎可以解决这个问题:

>>> 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]
Run Code Online (Sandbox Code Playgroud)