这是我一开始的资料。

我的清单

L = [0, 23, 234, 89, None, 0, 35, 9]

当我运行这个:

L = filter(None, L)

我得到了这个结果

[23, 234, 89, 35, 9]

但这不是我需要的,我真正需要的是:

[0, 23, 234, 89, 0, 35, 9]

因为我计算的是数据的百分位数0有很大的不同。

如何从列表中删除无值而不删除0值?


当前回答

假设列表如下

iterator = [None, 1, 2, 0, '', None, False, {}, (), []]

这将只返回bool(item)为True的项目

print filter(lambda item: item, iterator)
# [1, 2]

这相当于

print [item for item in iterator if item]

只过滤None:

print filter(lambda item: item is not None, iterator)
# [1, 2, 0, '', False, {}, (), []]

等价于:

print [item for item in iterator if item is not None]

获取所有值为False的项

print filter(lambda item: not item, iterator)
# Will print [None, '', 0, None, False, {}, (), []]

其他回答

列表理解可能是最干净的方式:

>>> L = [0, 23, 234, 89, None, 0, 35, 9
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

还有一种函数式编程方法,但它更复杂:

>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(partial(is_not, None), L))
[0, 23, 234, 89, 0, 35, 9]

如果列表中有NoneType和pandas._lib .missing. list。NAType对象比使用:

[i for i in lst if pd.notnull(i)]

假设列表如下

iterator = [None, 1, 2, 0, '', None, False, {}, (), []]

这将只返回bool(item)为True的项目

print filter(lambda item: item, iterator)
# [1, 2]

这相当于

print [item for item in iterator if item]

只过滤None:

print filter(lambda item: item is not None, iterator)
# [1, 2, 0, '', False, {}, (), []]

等价于:

print [item for item in iterator if item is not None]

获取所有值为False的项

print filter(lambda item: not item, iterator)
# Will print [None, '', 0, None, False, {}, (), []]
L = [0, 23, 234, 89, None, 0, 35, 9] 
result = list(filter(lambda x: x is not None, L))
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]

只是为了好玩,这里介绍了如何在不使用lambda的情况下调整过滤器来实现这一点,(我不建议使用此代码-仅用于科学目的)

>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(partial(is_not, None), L))
[0, 23, 234, 89, 0, 35, 9]