Python:filter(None,[list of bools])行为

Aut*_*tic 11 python

编辑:阅读建议的链接后,我不知道为什么这被标记为重复.起诉我.

任何人都可以帮助我理解为什么filter(None, [list of bools])删除False值?

请考虑以下事项:

low = 25 
high = 35
to_match = [15, 30, 32, 99]
def check(low, high, to_match):
    return [low <= i <= high for i in to_match]
Run Code Online (Sandbox Code Playgroud)

check(low, high, to_match) 回报 [False, True, True, False]

filter(None, check(low, high, to_match)) 回报 [True, True]

所以我想,Python必须考虑的FalseNone!令我惊讶的是,False is None回归False!

A)我错过了什么?

B)如何仅过滤None来自的值[True, None, False]

agf*_*agf 15

如果要过滤掉None,请使用:

filter(lambda x: x is not None, [list of bools])
Run Code Online (Sandbox Code Playgroud)

要么

[x for x in [list of bools] if x is not None]
Run Code Online (Sandbox Code Playgroud)

filter采取功能,而不是价值.filter(None, ...)是简写filter(lambda x: x, ...)- 它将过滤掉false-y的值(强调我的):

filter(function, iterable)

iterable根据function返回true的元素构造一个列表.iterable可以是序列,支持迭代的容器,也可以是迭代器.如果iterable是字符串或元组,则结果也具有该类型; 否则它总是一个列表.如果是Nonefunction,则假定为identity函数,即iterable删除所有false的元素.

注意,这filter(function, iterable)相当于[item for item in iterable if function(item)]if函数不是None,[item for item in iterable if item]如果函数是None.

  • 不过,您应该使用 `is not` 而不是 `!=`。 (2认同)

Pad*_*ham 5

对于python3,您可以None.__ne__只删除None,仅使用None过滤将删除所有false值,例如[], {} 0etc .:

filter(None.__ne__, check(low, high, to_match))
Run Code Online (Sandbox Code Playgroud)

对于python2,您需要添加一个lambda检查每个元素is not None

filter(lambda x: x is not None,....)
Run Code Online (Sandbox Code Playgroud)

如果您使用的是python2,请坚持使用列表组件:

[ele for ele in check(low, high, match) if ele is not None]
Run Code Online (Sandbox Code Playgroud)

使用filter的任何性能提升都会被lambda调用抵消,因此实际上最终会变慢。

  • 使用 `None.__ne__` 会发出警告:`&lt;stdin&gt;:1: DeprecationWarning: NotImplemented 不应在布尔上下文中使用` (2认同)