gpt4 book ai didi

python - 在 Python 中过滤列表,然后取消过滤

转载 作者:太空狗 更新时间:2023-10-30 01:51:13 26 4
gpt4 key购买 nike

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

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

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

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

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

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

我需要立即将整个筛选列表传递给函数 f()。我想知道是否有一种优雅的方法可以做到这一点,因为到目前为止我所有的解决方案都很困惑。这是我迄今为止最干净的一个:

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

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

最佳答案

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

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

关于python - 在 Python 中过滤列表,然后取消过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23880076/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com