Python, how to deploy tuples in lambda?

I have 2 lists of the same length, and I try to get them using a scalar product, 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 suitable for my task, is there a way to get lambda to work with tuples for such cases?

I would like to do something like

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

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

Thanks for the answers, you still need to learn a lot about Python)

+4
source share
6 answers

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

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

even zip() little less perfect ... to avoid creating a list, 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 the map separately:

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

and even then you didn’t need lambda, the available 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.

+19
source

You can just write

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

or use the card correctly:

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

map makes zip arguments, actually zip( .. ) is just map(None, ..) .

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

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

You can use the operator ( docs ) module:

  sum(map(lambda item: operator.mul(*item), zip(list1, list2))) 
+3
source
 sum(x[0]*x[1] for x in zip(list1, list2)) 

A list of generator concepts and expressions is the right way.

+2
source

The answer to the original OP question is about lambda accepting multiple arguments via zip.

You need to use parentheses around lambda arguments, for example:

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

Tested in Python 2.7

+1
source
 (lambda x: x[0] == ... and x[1] != ..... , mylistoftuples ) 

A tuple is a regular list item, so

 x <- {tuples...} 

So then x can simply be considered as a normal set (x1,x2,x..,xk) , like any other assigned set variable.

0
source

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


All Articles