如何在 lambda 表达式中的 If else 中继续?

问题描述 投票:0回答:2

我想在过滤中 lambda 表达式的 else 部分中继续。是否可以?如果是的话怎么办?谢谢你:)

filter_testing = list(filter((lambda element: element if 'w' in element else continue), lst_check))

python-3.x if-statement filter conditional-statements continue
2个回答
0
投票

传递给过滤器的函数应该返回一个布尔值,而不是元素:

filter_testing = list(filter((lambda element: 'w' in element), lst_check))

参见:https://www.w3schools.com/python/ref_func_filter.asp


0
投票

如果不满足条件,您可以提供 False:

list(filter(lambda element: element if "w" in element else False,
            ["with", "or", "without", "you"]))

结果(Python 3.9.13):

['with', 'without']

文档中这句话的提示:

如果function

None
,则假设恒等函数,即所有 iterable 中为 false 的元素将被删除。 Python 文档:内置函数

© www.soinside.com 2019 - 2024. All rights reserved.