这是我一开始的资料。
我的清单
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值?
当前回答
如果列表中有NoneType和pandas._lib .missing. list。NAType对象比使用:
[i for i in lst if pd.notnull(i)]
其他回答
>>> 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]
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))
使用列表理解可以做到如下:
l = [i for i in my_list if i is not None]
l的值为:
[0, 23, 234, 89, 0, 35, 9]
L = [0, 23, 234, 89, None, 0, 35, 9]
result = list(filter(lambda x: x is not None, L))
如果列表中有NoneType和pandas._lib .missing. list。NAType对象比使用:
[i for i in lst if pd.notnull(i)]