list(filter(None,[1,0,False,True]))
返回[1, True]
为什么不是0,False??不应该是这两个符合条件的吗?
这种事情就找python官方文档,在3.9.6文档的内置函数中有如下描述
从 filter()底层代码来看
class filter(object):
"""
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true.
"""
def __getattribute__(self, *args, **kwargs): # real signature unknown
""" Return getattr(self, name). """
pass
def __init__(self, function_or_None, iterable): # real signature unknown; restored from __doc__
pass
def __iter__(self, *args, **kwargs): # real signature unknown
""" Implement iter(self). """
pass
@staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass
def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass
def __reduce__(self, *args, **kwargs): # real signature unknown
""" Return state information for pickling. """
pass
filter(function or None, iterable) 会返回一个迭代器,该迭代器产生iterable函数中的(item)为真的那些项。
如果function为None,则返回为true的项,也就是为真的项。
相当于-->示例中的结果:
def func(item):
if 1 == item:
return item
a = list(filter(func, [1, 0, False, True]))
print(a)
#结果为:
[1, True]
也就是当你传入None 时代表的就是返回真, 且也只返回真
这是过滤掉类型为false的,可以记得采纳哦