How to use reduce function in tuple list?

I have this list of tuples:

a = [(1, 2), (1, 4), (1, 6)] 

I would like to use the decrease function to get this result:

  (3, 12) 

I tried:

  x = reduce(lambda x, y: x+y, a) 

But I get an error message ... I want to add all the elements in the first index of each tuple, and then add the second element.

+6
source share
4 answers

If you want the output of reduce be a tuple, all intermediate results should also be a tuple.

 a = [(1, 2), (1, 4), (1, 6)] print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), a) 

Output

 (3, 12) 

Edit: If you want to get (0, 0) when the list is empty

 a = [] print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), [(0, 0)] + a) 

Output

 (0, 0) 

Edit 2: Reduce accepts the default initializer as the last parameter, which is optional. Using this, the code becomes

 a = [] print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), a, (0, 0)) 
+10
source
 >>> a = [(1, 2), (1, 4), (1, 6)] >>> map(sum, zip(*a)) [3, 12] 

UPDATE

According to Raymond Hettinger,

The zip-star trick abuses the stack in order to calculate transpose expensively.

Here's an alternative that doesn't use list comprehension.

 >>> a = [(1, 2), (1, 4), (1, 6)] >>> [sum(item[i] for item in a) for i in range(2)] # 2 == len(a[0]) [3, 12] >>> a = [] >>> [sum(item[i] for item in a) for i in range(2)] # 2 == len(a[0]) [0, 0] 
+5
source

You were close. Just change your code to unzip input tuples first. When you add new values, just repack the result tuple:

 >>> a = [(1, 2), (1, 4), (1, 6)] >>> reduce(lambda (sx, sy), (x, y): (sx+x, sy+y), a) (3, 12) 
+3
source

Try the following:

 >>> from numpy import asarray >>> a = asarray([(1, 2), (1, 4), (1, 6)]) >>> reduce(lambda x,y:x+y, a) array([ 3, 12]) 
0
source

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


All Articles