Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, how to unroll tuples in lambda?

Tags:

python

lambda

I have 2 equal-length lists and I am trying to get scalar product of them with, but it does not work this way:

sum(map(lambda a,b: a*b, zip(list1, list2)))

error: TypeError: <lambda>() takes exactly 2 arguments (1 given)

Even if this code is not good for my task, is there any way to force lambda to work with tuples for such cases?

i'd like to do something like

lambda x: (a,b)=x;a*b 

But it will not work with C-style ';' )

Thank you for answers, still need to learn many things about Python )

like image 963
ShPavel Avatar asked Nov 28 '22 07:11

ShPavel


2 Answers

well, you don't need a lambda for this...

sum(a*b for a, b in zip(list1, list2))

even zip() is slightly less than perfect... to avoid creating a list, either use python3, or itertools.izip:

sum(a*b for a, b in itertools.izip(list1, list2))

but if, for some craaaaazy reason, you really really wanted to use lambda, pass each list to map seperately:

sum(map(lambda a, b: a*b, list1, list2))

and even then, you didn't need a lambda either, a callable product is available in the operator module:

sum(map(operator.mul, list1, list2))

but use the generator in the first or second example, it will usually be faster.

like image 148
SingleNegationElimination Avatar answered Dec 11 '22 02:12

SingleNegationElimination


You can simply write

sum(a*b for a,b in zip(list1, list2))

or use map correctly:

sum(map(lambda (a,b): a*b, list1, list2))

map does zip it's arguments, in fact zip( .. ) is just map(None, ..).

You can also unpack arguments when the function is called in Python2, but this unusual feature was removed in 3:

sum(map((lambda (a,b): a*b), zip(list1, list2)))
like image 44
Jochen Ritzel Avatar answered Dec 11 '22 02:12

Jochen Ritzel