Does Python reduce error?

The following is my python code:

>>> item = 1 >>> a = [] >>> a.append((1,2,3)) >>> a.append((7,2,4)) >>> sums=reduce(lambda x:abs(item-x[1]),a) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: <lambda>() takes exactly 1 argument (2 given) >>> 

How can i fix this? Thanks!

+4
source share
3 answers

Your lambda takes only one argument, but reduce requires a function that takes two arguments. Make your lambda two arguments.

Since you did not say that you want this code to work, I just guess:

 the_sum=reduce(lambda x,y:abs(y[1]-x[1]),a) 
+8
source

Your problem in itself is a bit unclear. Anyway, I just accepted the assumption -

 >>> a = [] >>> a.append((1,2,3)) >>> a.append((7,2,4)) >>> a [(1, 2, 3), (7, 2, 4)] # list of tuples 

I assume that you may be interested in getting the sum of all the items in the list. If this is a problem, then this can be solved in 2 steps.

1) The first step is to smooth the list.

2) Then add all the items in the list.

 >>> new_list = [y for x in a for y in x] # List comprehension used to flatten the list [1, 2, 3, 7, 2, 4] >>> sum(new_list) 19 

Single liner

 >>> sum([y for x in a for y in x]) 19 

Another suggestion, if your problem is to minus each tuple element over an element in the list, use this:

 >>> [tuple(map(lambda y: abs(item - y), x)) for x in a] [(0, 1, 2), (6, 1, 3)] # map function always returns a list so i have used tuple function to convert it into tuple. 

If the problem is something else, please clarify.

PS: understanding Python List is much better and most effective.

+3
source

reduce expects the function to be given to accept 2 arguments. For each element in iterable, it will pass the function to the current element and the previous return value from the function. So, getting the sum of the reduce(lambda: x,y: x+y, l, 0) list reduce(lambda: x,y: x+y, l, 0)

If I understood correctly, in order to get the behavior you were trying to get, change the code to:

 a_sum = reduce(lambda x,y: x + abs(item-y[1]), a, 0) 

But I may be wrong in what you tried to get. For more information, see the docstring of the reduce function.

+2
source

All Articles