这是我一开始的资料。

我的清单

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值?


当前回答

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

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

其他回答

from operator import is_not
from functools import partial   

filter_null = partial(filter, partial(is_not, None))

# A test case
L = [1, None, 2, None, 3]
L = list(filter_null(L))

假设列表如下

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, {}, (), []]

@jamylak的回答非常好,但是如果你不想导入几个模块来完成这个简单的任务,就在原地写你自己的lambda:

>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> filter(lambda v: v is not None, L)
[0, 23, 234, 89, 0, 35, 9]

使用列表理解可以做到如下:

l = [i for i in my_list if i is not None]

l的值为:

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

如果这都是列表的列表,你可以修改sir @Raymond的答案

L = [[None], [123], [None], [151]] no_none_val = list(filter(无。__ne__, [x[0] for x in L])) 然而对于python2

no_none_val = [x[0] for x in L if x[0] not None] """ Both returns [123, 151]""" "

如果变量不是List中的变量,<< list_index[0]无>>