[英]Lambda function - Unknown number of arguments
Currently, this is how I resolve a "and" function using lambda with two arguments: 当前,这是我如何使用带有两个参数的lambda解析“ and”函数的方法:
custom_function = lambda a, b: a and b
But how can I resolve an unknown number of arguments, like: 但是,如何解决未知数量的参数,例如:
custom_function = lambda a, b, c, d, ...: what now?
Anybody had this issue before? 有人以前有这个问题吗?
Thanks and Greetings! 谢谢和问候!
You can use "*args": 您可以使用“ * args”:
>>> custom_function = lambda *args: all(args)
>>> custom_function(1, 2, 3)
True
>>> custom_function(1, 2, 3, 0)
False
Which indeed is the same as just using "all": 确实与仅使用“ all”相同:
>>> all(1, 2, 3)
True
>>> all(1, 2, 3, 0)
False
To be general, you can use "functools.reduce" to use any "2-parameters" function with any number of parameters (if their order doesn't matter): 一般而言,您可以使用“ functools.reduce”将带有任何数量参数的“ 2-parameters”函数(如果它们的顺序无关紧要)使用:
import operator
import functools
c = lambda *args: functools.reduce(operator.and_, args)
(same results as before) (结果与以前相同)
You can use argument unpacking via the *
operator to process any number of arguments. 您可以通过
*
运算符使用参数解包来处理任意数量的参数。 You would have to resort to reduce
(Python2) or functools.reduce
(Python3) in order to combine them all with and
in a single expression (as needed by the lambda): 您必须求助于
reduce
(Python2)或functools.reduce
(Python3),以便将它们全部组合在一起and
在一个表达式中(根据lambda的需要):
from functools import reduce # only Py3
custom_function = lambda *args: reduce(lambda x, y: x and y, args, True)
Note: this is not the same as all
, like many here suggest: 注意:这与
all
,这里有很多建议:
>>> all([1,2,3])
True
>>> 1 and 2 and 3
3
>>> custom_function(1,2,3)
3
Why not just using the all function? 为什么不仅仅使用all功能呢?
a = 1
b = 2
c = None
args = [a, b, c]
print (all(args))
# False
First, use *args
to store an unknown number of arguments as a tuple. 首先,使用
*args
将未知数量的参数存储为元组。
Second, all(args)
only return Ture
or False
but and
operation may return value ( Here is why). 其次,
all(args)
只返回Ture
或False
,但and
操作可以返回值( 在这里是为什么)。 So we need to use reduce
. 所以我们需要使用
reduce
。
Here is the solution: 解决方法如下:
custom_function = lambda *args: reduce(lambda x,y: x and y, args)
Test 1: arguments are Ture or False 测试1:参数为Ture或False
>>> custom_function(True,False,True,False)
False
>>> custom_function(True,True,True)
True
Test 2: arguments are values 测试2:参数是值
>>> custom_function(1,2,3,4,3,2)
2
>>> custom_function('a','b','d','s')
's'
Test 3: arguments are a combination of bool and values 测试3:参数是布尔值和值的组合
>>> custom_function(1,2,True,4,3,2)
2
>>> custom_function(1,2,False,4,3,2)
False
Note the three tests are correct according to the definition of Logical AND (and): 请注意,根据逻辑与 (和)的定义,这三个测试是正确的:
Return the first Falsey value if there are any, else return the last value in the expression.
如果有,则返回第一个Falsey值,否则返回表达式中的最后一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.