这是我一开始的资料。
我的清单
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]
当我运行这个:
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, {}, (), []]
其他回答
@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]
假设列表如下
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, {}, (), []]
如果列表中有NoneType和pandas._lib .missing. list。NAType对象比使用:
[i for i in lst if pd.notnull(i)]
L = [0, 23, 234, 89, None, 0, 35, 9]
result = list(filter(lambda x: x is not None, L))
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))