简体   繁体   中英

Lambda function - Unknown number of arguments

Currently, this is how I resolve a "and" function using lambda with two arguments:

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":

>>> 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(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):

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):

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([1,2,3])
True
>>> 1 and 2 and 3
3
>>> custom_function(1,2,3)
3

Why not just using the all function?

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.

Second, all(args) only return Ture or False but and operation may return value ( Here is why). So we need to use reduce .

Here is the solution:

custom_function = lambda *args: reduce(lambda x,y: x and y, args)

Test 1: arguments are Ture or False

>>> custom_function(True,False,True,False)
False
>>> custom_function(True,True,True)
True

Test 2: arguments are values

>>> 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

>>> 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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