I have this this list of tuple:
a = [(1, 2), (1, 4), (1, 6)]
I would like to use the reduce function in order to get this result:
(3, 12)
I tried:
x = reduce(lambda x, y: x+y, a)
But i get an error...I want to add up all the elements in the first index of each tuple, then add up the second element.
Python's reduce() is a function that implements a mathematical technique called folding or reduction. reduce() is useful when you need to apply a function to an iterable and reduce it to a single cumulative value.
Python offers a function called reduce() that allows you to reduce a list in a more concise way. The reduce() function applies the fn function of two arguments cumulatively to the items of the list, from left to right, to reduce the list into a single value.
Practical Data Science using Python When it is required to subtract the tuples, the 'map' method and lambda function can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.
Use the del statement to remove a tuple from a list of tuples, e.g. del list_of_tuples[0] . The del statement can be used to remove a tuple from a list by its index, and can also be used to remove slices from a list of tuples.
If you want the output of a reduce
to be a tuple, all the 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 default initializer as the last parameter, which is optional. By using that, the code becomes
a = []
print reduce(lambda x, y: (x[0] + y[0], x[1] + y[1]), a, (0, 0))
>>> a = [(1, 2), (1, 4), (1, 6)]
>>> map(sum, zip(*a))
[3, 12]
UPDATE
According to Raymond Hettinger,
zip-star trick abuses the stack to expensively compute a transpose.
Here's an alternative that does not 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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With