gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:39:25 25 4
gpt4 key购买 nike

编辑:阅读建议的链接后,我不知道为什么它被标记为重复。告我。

谁能帮我理解为什么 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]

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) 如何从 [True, None, False] 中仅过滤 None 值?

最佳答案

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

filter(lambda x: x is not None, [list of bools])

[x for x in [list of bools] if x is not None]

filter takes a function, not a value . filter(None, ...)filter(lambda x: x, ...) 的简写——它将过滤掉 false-y 的值(强调我的):

filter(function, iterable)

Construct a list from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If iterable is a string or a tuple, the result also has that type; otherwise it is always a list. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed.

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None.

关于Python: filter(None, [list of bools]) 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38339496/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com