Arguments with unpacking lambda

In Python 2, this code is fine:

f = lambda (m, k): m + k m = [1,2,3,4] k = [5,6,7,8] print(map(f, zip(m, k))) 

but in Python 3, an error occurred:

 f = lambda (m, k): m + k ^ SyntaxError: invalid syntax 

If I remove the parentheses in the lambda expression, another error occurs:

 TypeError: <lambda>() missing 1 required positional argument: 'k' 

Also a tuple approach, since a single lambda argument works in Python 3, but it is not clear (hard to read):

 f = lambda args: args[0] + args[1] 

How can I decompress values โ€‹โ€‹correctly in Python 3?

+5
source share
6 answers

Removing tuple unpacking is discussed in PEP 3113 . Basically, you cannot do this in Python 3. Under the Transition Plan heading, you see that the โ€œsuggestedโ€ way to do this is as your final code:

 lambda x_y: x_y[0] + x_y[1] 
+6
source

You can use the same syntax in both Python 2 and Python 3 if you use itertools.starmap instead of map , which unpacks a tuple of items for us:

 >>> from itertools import starmap >>> f = lambda m, k: m + k >>> list(starmap(f, zip(m, k))) [6, 8, 10, 12] 
+5
source

You cannot use parentheses in Python3 to unpack arguments in lambda functions ( PEP 3113 ), try:

 f = lambda m, k: m + k 

For it to work with your code, you must use:

 lambda mk: mk[0] + mk[1] 
+2
source

This solution is easier to find:

 lambda mk: (lambda m,k: m + k)(*mk) 

In addition, I argue that unpacking does this more than (1) Pythonic and (2) is consistent with manually unpacking tuples for named functions required in Python 3 PEP 3113 .

+1
source

Or you can just sum () add numbers without unpacking:

 f = lambda args: sum(args) 
0
source

Just use

 map(f, m, k) 

Note that f may be

 from operator import add map(add, m, k) 
0
source

Source: https://habr.com/ru/post/1210386/


All Articles