简体   繁体   English

带有 if 但没有 else 的 Python lambda

[英]Python lambda with if but without else

I was writing some lambda functions and couldn't figure this out.我正在编写一些 lambda 函数,但无法弄清楚。 Is there a way to have something like lambda x: x if (x<3) in python?有没有办法在 python 中有类似lambda x: x if (x<3)的东西? As lambda a,b: a if (a > b) else b works ok.作为lambda a,b: a if (a > b) else b工作正常。 So far lambda x: x < 3 and x or None seems to be the closest i have found.到目前为止lambda x: x < 3 and x or None似乎是我发现的最接近的。

A lambda, like any function, must have a return value.与任何函数一样,lambda 必须有返回值。

lambda x: x if (x<3) does not work because it does not specify what to return if not x<3 . lambda x: x if (x<3)不起作用,因为它没有指定如果不是x<3则返回什么。 By default functions return None , so you could do默认情况下,函数返回None ,所以你可以这样做

lambda x: x if (x<3) else None

But perhaps what you are looking for is a list comprehension with an if condition.但也许您正在寻找的是带有if条件的列表理解。 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]

I found that filter provided exactly what I was looking for in python 2:我发现filter提供了我在 python 2 中寻找的内容:

>>> data = [1, 2, 5, 10, -1]
>>> filter(lambda x: x < 3, data)
[1, 2, -1]

The implementation is different in 2.x and 3.x : while 2.x provides a list, 3.x provides an iterator. 2.x3.x的实现不同:2.x 提供列表,3.x 提供迭代器。 Using a list comprehension might make for a cleaner use in 3.x:在 3.x 中使用列表推导可能会更简洁:

>>> data = [1, 2, 5, 10, -1]
>>> [filter(lambda x: x < 3, data)]
[1, 2, -1]

lambda x: x if x < 3 else None有什么问题?

You can always try to invoke 'filter' for conditional checks.您始终可以尝试调用“过滤器”进行条件检查。 Fundamentally, map() has to work on every occurrence of the iterables, so it cannot pick and choose.从根本上说, map()必须对每次出现的可迭代对象起作用,因此它无法进行选择。 But filter may help narrow down the choices.但过滤器可能有助于缩小选择范围。 For example, I create a list from 1 to 19 but want to create a tuple of squares of only even numbers.例如,我创建了一个从 1 到 19 的列表,但想创建一个只有偶数平方的元

x = list(range(1,20))

y = tuple(map(lambda n: n**2, filter(lambda n: n%2==0,x)))

print (y)

You can use ellipsis ... to fill else statement您可以使用省略号...来填充else语句

lambda x: x if (x<3) else ... 

Note it does not work with pass .请注意,它不适用于pass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM