带if但不带else的Python lambda
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12709062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python lambda with if but without else
提问by root
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 bworks ok. So far lambda x: x < 3 and x or Noneseems to be the closest i have found.
我正在编写一些 lambda 函数,但无法弄清楚。有没有办法lambda x: x if (x<3)在python中拥有类似的东西?由于lambda a,b: a if (a > b) else b工程确定。到目前为止lambda x: x < 3 and x or None似乎是我发现的最接近的。
采纳答案by unutbu
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. By default functions return None, so you could do
lambda x: x if (x<3)不起作用,因为它没有指定如果没有返回什么x<3。默认情况下,函数 return None,所以你可以这样做
lambda x: x if (x<3) else None
But perhaps what you are looking for is a list comprehension with an ifcondition. For example:
但也许您正在寻找的是带有if条件的列表理解。例如:
In [21]: data = [1, 2, 5, 10, -1]
In [22]: [x for x in data if x < 3]
Out[22]: [1, 2, -1]
回答by user4815162342
What's wrong with lambda x: x if x < 3 else None?
怎么了lambda x: x if x < 3 else None?
回答by linuxraptor
Sorry to resuscitate a zombie.
抱歉让僵尸复活。
I was looking for an answer to the same question, and I found that "filter" provided exactly what I was looking for:
我正在寻找同一问题的答案,我发现“过滤器”提供了我正在寻找的内容:
>>> data = [1, 2, 5, 10, -1]
>>> filter(lambda x: x < 3, data)
[1, 2, -1]
The implementation is the same in both 2.x and 3.x: https://docs.python.org/2/library/functions.html#filterhttps://docs.python.org/3/library/functions.html#filter
2.x 和 3.x 中的实现是相同的:https: //docs.python.org/2/library/functions.html#filter https://docs.python.org/3/library/functions。 html#过滤器
回答by Tirtha
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. But filter may help narrow down the choices. For example, I create a list from 1 to 19 but want to create a tuple ofsquares of only even numbers.
您始终可以尝试调用“过滤器”进行条件检查。从根本上说,map()必须处理每次出现的可迭代对象,因此它无法进行挑选。但过滤器可能有助于缩小选择范围。例如,我创建了一个从 1 到 19 的列表,但想创建一个只有偶数的平方元组。
x = list(range(1,20))
y = tuple(map(lambda n: n**2, filter(lambda n: n%2==0,x)))
print (y)

