带有if但不包含else的Python lambda [英] Python lambda with if but without else
问题描述
我正在编写一些lambda函数,无法弄清楚.有没有办法在python中有类似lambda x: x if (x<3)
的东西?由于lambda a,b: a if (a > b) else b
可以正常工作.到目前为止,lambda x: x < 3 and x or None
似乎是我找到的最接近的东西.
I was writing some lambda functions and couldn't figure this out. Is there a way to have something like lambda x: x if (x<3)
in python? As lambda a,b: a if (a > b) else b
works ok. So far lambda x: x < 3 and x or None
seems to be the closest i have found.
推荐答案
lambda与任何函数一样,必须具有返回值.
A lambda, like any function, must have a return value.
lambda x: x if (x<3)
不起作用,因为它没有指定如果不是x<3
会返回的内容.默认情况下,函数返回None
,所以您可以这样做
lambda x: x if (x<3)
does not work because it does not specify what to return if not x<3
. By default functions return None
, so you could do
lambda x: x if (x<3) else None
但是也许您正在寻找的是具有if
条件的列表理解.例如:
But perhaps what you are looking for is a list comprehension with an if
condition. For example:
In [21]: data = [1, 2, 5, 10, -1]
In [22]: [x for x in data if x < 3]
Out[22]: [1, 2, -1]
这篇关于带有if但不包含else的Python lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!