Using Python shortens the list of pairs

I'm trying to combine a bunch of items in a list to create a destination object, in a way that is similar to creating a sum of objects. I am trying to use a simple option on reduce where you are looking at a list of pairs, rather than a flat list, to do this. I want to do something like:

 nums = [1, 2, 3] reduce(lambda x, y: x + y, nums) 

except that I would like to add additional information to the amount that applies to each item in the nums list of numbers. For example, for each pair (a, b) in the list, execute the sum as (a + b):

 nums = [(1, 0), (2, 5), (3, 10)] reduce(lambda x, y: (x[0]+x[1]) + (y[0]+y[1]), nums) 

This does not work:

 >>> reduce(lambda x, y: (x[0]+x[1]) + (y[0]+y[1]), nums) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> TypeError: 'int' object is unsubscriptable 

Why is this not working? I know that I can encode nums as a flat list - this is not the main thing - I just want to be able to create a reduction operation that can iterate over a list of pairs or more than two lists of the same length at the same time and pool information from both lists. thanks.

+6
source share
1 answer

Looking at the lambda, you switched to reduce :

 f = lambda x, y: (x[0]+x[1]) + (y[0]+y[1]) 

The value returned by f will be passed as a parameter to another call to f . But while f expects its parameters to be pairs, the return value will be int . You need to make this function return a pair. For example, this sums the left and right sides separately:

 >>> nums = [(1, 0), (2, 5), (3, 10)] >>> reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), nums) (6, 15) 

Another thing you can do is handle the accumulated value differently outside the list items: you can make the accumulated value a int , and the list items can be pairs. If you do this, you must pass the initializer argument to reduce so that the battery is correctly initialized to int :

 >>> nums = [(1, 0), (2, 5), (3, 10)] >>> reduce(lambda acc, y: acc + y[0] + y[1], nums, 0) 21 
+6
source

All Articles